缺少函数签名上的生命周期说明符

缺少函数签名上的生命周期说明符

本文介绍了缺少函数签名上的生命周期说明符 [E0106]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个简单代码中的错误感到非常困惑(游乐场):

I'm pretty confused by the errors from this simple code (Playground):

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

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

fn fn2() -> &str {
    "12345abc"
}

这些是:

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

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

I haven't been faced with these errors before, has anything changed in a recent Rust version? How can I fix the errors?

推荐答案

很久以前,当一个函数返回一个借用的指针时,编译器会推断出'static的生​​命周期,所以fn2 将成功编译.从那时起,就实施了终生省略.生命周期省略是一个过程,编译器会自动将输入参数的生命周期与输出值的生命周期相关联,而无需显式命名它.

A long time ago, when a function returned a borrowed pointer, the compiler inferred the 'static lifetime, so fn2 would compile successfully. Since then, lifetime elision has been implemented. Lifetime elision is a process where the compiler will automatically link the lifetime of an input parameter to the lifetime of the output value without having to explicitly name it.

例如,fn1,没有生命周期省略,会写成这样:

For example, fn1, without lifetime elision, would be written like this:

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

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

However, fn2 has no parameters that are borrowed pointers or structs with lifetime parameters (indeed, it has no parameters at all). You must therefore mention the lifetime explicitly. Since you're returning a string literal, the correct lifetime is 'static (as suggested by the compiler).

fn fn2() -> &'static str {
    "12345abc"
}

这篇关于缺少函数签名上的生命周期说明符 [E0106]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:26