首先,以下代码是正确的:
fn main() {
let a = &get_i32();
println!("{}", a);
}
fn get_i32() -> i32 {
return 100;
}
但以下代码出现错误:
fn main() {
let a;
a = &get_i32();
println!("{}", a);
}
error[E0716]: temporary value dropped while borrowed
--> src/bin/rust_course.rs:8:10
|
8 | a = &get_i32();
| ^^^^^^^^^- temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
9 | println!("{}", a);
| - borrow later used here
|
help: consider using a `let` binding to create a longer lived value
|
8 ~ let binding = get_i32();
9 ~ a = &binding;
|
For more information about this error, try `rustc --explain E0716`.
这两段代码之间的本质区别是什么?我知道&get_i32()
总是返回一个临时值,所以它应该总是报告一个错误.
一个类似的问题:
fn main() {
let s1 = &String::from("hello world");
println!("{}", s1);
let s2 = String::from("hello world").as_str();
println!("{}", s2);
}
error[E0716]: temporary value dropped while borrowed
--> src/bin/rust_course.rs:6:14
|
6 | let s2 = String::from("hello world").as_str();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary value which is freed while still in use
7 | println!("{}", s2);
| -- borrow later used here
|
help: consider using a `let` binding to create a longer lived value
|
6 ~ let binding = String::from("hello world");
7 ~ let s2 = binding.as_str();
|
For more information about this error, try `rustc --explain E0716`.
S1和S2有什么不同?
还有一个更类似的问题:
fn main() {
print(String::from("hello world").as_str());
}
fn print(str: &str) {
println!("{}", str);
}
上面的代码是正确的,但我不明白为什么String::from("hello world").as_str()
可以传递给函数,而不能赋值给变量.