Sub topic 7
Lifetime elision: when you can leave annotations out
This chapter assumes you can read basic lifetime annotations such as &'a str and know why longest<'a> needs one. Here you learn the three rules the compiler applies to fill in lifetimes you did not write.
What elision is
Lifetime elision is a set of fixed rules that let the compiler infer lifetimes in function and method signatures. It is not a guess. If the rules produce a complete answer, you can omit the annotations. If they do not, the compiler stops and asks you to write them.
Elision only looks at the signature. It never reads the function body.
The three rules
Input lifetimes are those on parameters. Output lifetimes are those on the return type.
- Each elided lifetime in the parameters becomes its own separate lifetime parameter.
- If there is exactly one input lifetime, it is assigned to every elided output lifetime.
- If there are several input lifetimes but one of them is
&selfor&mut self, the lifetime ofselfis assigned to every elided output lifetime.
If an output lifetime is still unknown after these rules, the compiler reports error E0106.
Rule 2 in practice
first_word has one input reference, so rule 2 applies.
// What you write:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
// What the compiler infers after elision:
fn first_word_explicit<'a>(s: &'a str) -> &'a str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
println!("{}", first_word("hello world"));
println!("{}", first_word_explicit("good morning"));
}Both signatures mean the same thing.
When elision fails
With two reference parameters and no self, no rule picks an output lifetime.
// Does not compile:
// fn longest(x: &str, y: &str) -> &str {
// if x.len() > y.len() { x } else { y }
// }
// error[E0106]: missing lifetime specifierRule 1 gives x and y different lifetimes. Rule 2 needs exactly one input. Rule 3 needs self. The compiler cannot tell whether the result comes from x or y, so you must say so with longest<'a>(x: &'a str, y: &'a str) -> &'a str.
Rule 3 in methods
Methods are where rule 3 helps most.
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn announce_and_return(&self, announcement: &str) -> &str {
println!("Attention: {announcement}");
self.part
}
}
fn main() {
let e = Excerpt { part: "Call me Ishmael" };
println!("{}", e.announce_and_return("hello"));
}The returned &str is tied to &self, not to announcement. That is the right choice here because the method returns self.part.
Rule 3 is only a default. If a method returned announcement instead, the elided signature would be wrong and the compiler would reject the body. You would then annotate the signature explicitly.
The anonymous lifetime `'_`
You can write '_ to say "an elided lifetime goes here." It is useful when a type has a lifetime parameter that you do not need to name.
struct Excerpt<'a> {
part: &'a str,
}
impl Excerpt<'_> {
fn level(&self) -> i32 {
3
}
}
fn main() {
let e = Excerpt { part: "text" };
println!("{} {}", e.level(), e.part);
}Exercise
Does fn pick(a: &str, b: &str) -> &str compile without annotations? Explain using the rules.
Show answer
No. Rule 1 gives a and b separate lifetimes. Rule 2 does not apply because there are two input lifetimes. Rule 3 does not apply because there is no self. The output lifetime stays unknown, so the compiler reports E0106. Fix it with fn pick<'a>(a: &'a str, b: &'a str) -> &'a str.