函数签名上缺少生命周期说明符[E0106]

アレッ*_*ックス 8 rust

我很困惑这个简单代码(Playground)的错误:

fn main() {
    let a = fn1("test123");
}

fn fn1(a1: &str) -> &str {
    let a = fn2();
    a
}

fn fn2() -> &str {
    "12345abc"
}
Run Code Online (Sandbox Code Playgroud)

这些是:

error[E0106]: missing lifetime specifier
  --> <anon>:10:13
   |
10 | fn fn2() -> &str {
   |             ^ expected 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 giving it a 'static lifetime
Run Code Online (Sandbox Code Playgroud)

我以前没有遇到过这些错误,在最近的Rust版本中有什么变化吗?我该如何修复错误?

Fra*_*gné 16

很久以前,当一个函数返回一个借来的指针时,编译器推断出了'static生命周期,因此fn2编译成功.从那时起,终身省略已经实施.Lifetime elision是一个过程,编译器会自动将输入参数的生命周期链接到输出值的生命周期,而不必明确命名它.

例如,fn1没有终身省略,将会这样写:

fn fn1<'a>(a1: &'a str) -> &'a str {
    let a = fn2();
    a
}
Run Code Online (Sandbox Code Playgroud)

但是,fn2没有带有生命周期参数的借用指针或结构的参数(事实上,它根本没有参数).因此,您必须明确提及生命周期.由于您返回的是字符串文字,因此正确的生命周期'static(正如编译器所建议的那样).

fn fn2() -> &'static str {
    "12345abc"
}
Run Code Online (Sandbox Code Playgroud)