这不是一个典型的问题,而是一个典型的问题.鉴于以下代码:
fn foo() -> Result<String, i32> {
return Ok("world".to_string());
}
fn bar() -> Result<String, i32> {
let mut value = String::new();
value.push_str(&try!(foo())); // this line here
return Ok("Hello ".to_string() + &value);
}
fn main() {
match bar() {
Ok(message) => println!("{}", message),
_ => return,
}
}
Rust返回错误:
<std macros>:3:43: 3:46
error: mismatched types:
expectedstr
,
foundcollections::string::String
(expectedstr
,
found structcollections::string::String
) [E0308]
<std macros>:3 $ crate:: result:: Result:: Ok ( val ) => val , $ crate:: result:: Result::
<std macros>:1:1: 6:48
note: in expansion oftry!
<std macros>:3:43: 3:46
help: runrustc --explain E0308
to see a detailed explanation
error: aborting due to previous error
如果我捕获try!
的结果,并分别将&
应用于结果,它会工作(并打印出Hello world
):
fn foo() -> Result<String, i32> {
return Ok("world".to_string());
}
fn bar() -> Result<String, i32> {
let mut value = String::new();
let foo_result = try!(foo()); // capture the result of try!
value.push_str(&foo_result); // now use the result with &
return Ok("Hello ".to_string() + &value);
}
fn main() {
match bar() {
Ok(message) => println!("{}", message),
_ => return,
}
}
为什么let foo_result = try!(foo()); value.push_str(&foo_result);
行而value.push_str(&try!(foo()));
不行?从我天真的Angular 来看,它们似乎是等价的,所以我不确定我不了解 rust 迹的哪个关键部分.