E0106: missing lifetime specifier
A reference is only valid while the thing it points at is alive. When a function returns a reference, the compiler needs to know which input it borrows from so it can guarantee the caller never holds a dangling pointer.
Lifetimes like `'a` are not runtime values and cost nothing. They are annotations that let the compiler check that relationship.
Code that triggers it
fn longest(a: &str, b: &str) -> &str { // error[E0106]
if a.len() > b.len() { a } else { b }
}Code that compiles
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() > b.len() { a } else { b }
}
fn main() {
println!("{}", longest("ownership", "borrowing"));
}Introduce a lifetime parameter `'a` and tie the inputs and the return value together. If the returned data does not actually come from an input, return an owned `String` instead.
Try both versions
The broken version is loaded below so you can see the real compiler message, then fix it yourself.
Contrast AAA · 16.6:1
15px