Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

rust - missing lifetime specifier [E0106] on function signature

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"
}

These are:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

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

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"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...