我是 Rust 的新手。这里有两个函数。当我编译时,foo1 编译通过,foo2 显示错误。但与foo2相比,他们只给foo1添加了一个不相关的参数,这是什么原因?
fn main() {
let a = 33;
let x = foo1(&a);
let y = foo2();
println!("{x} {y}");
}
fn foo1(_a: &i32) -> &str {
let x = "ddd";
return x;
}
fn foo2() -> &str {
let x = "ddd";
return x;
}
➜ src git:(master) ✗ rustc -V
rustc 1.73.0 (cc66ad468 2023-10-03)
➜ src git:(master) ✗ rustc main.rs
error[E0106]: missing lifetime specifier
--> main.rs:13:14
|
13 | fn foo2() -> &str {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime
|
13 | fn foo2() -> &'static str {
| +++++++
error: aborting due to previous error
For more information about this error, try `rustc --explain E0106`.
因为
foo1()
有一个引用作为参数,为了方便起见,编译器假设返回的引用与参数具有相同的生命周期(这在实践中几乎总是正确的)。 let x_out = {
let a = 33;
let x_in = foo1(&a);
x_in
};
在这里,编译器会抱怨,因为
x_out
会比 a
寿命更长。foo1()
,我们可以看到结果没有引用任何与参数相关的内容。-> &'static str
。
在
foo2()
中,这种便利甚至无法实现,因为没有引用作为参数。-> &'static str
。