这两个功能有什么区别?他们看起来一样

问题描述 投票:0回答:1

我是 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`.
rust lifetime difference
1个回答
1
投票

因为

foo1()
有一个引用作为参数,为了方便起见,编译器假设返回的引用与参数具有相同的生命周期(这在实践中几乎总是正确的)。
您可以通过这些稍加修改的行来看到这一点:

    let x_out = {
        let a = 33;
        let x_in = foo1(&a);
        x_in
    };

在这里,编译器会抱怨,因为

x_out
会比
a
寿命更长。
当然,查看
foo1()
,我们可以看到结果没有引用任何与参数相关的内容。
这里的便利性具有误导性,我们应该写成
-> &'static str

foo2()
中,这种便利甚至无法实现,因为没有引用作为参数。
我们别无选择,只能明确表达生命周期
-> &'static str

© www.soinside.com 2019 - 2024. All rights reserved.