Sub topic 9
When you can omit lifetimes: elision rules
This chapter assumes you can write functions that take &T and &mut T, and that you know why a returned reference must not outlive the data it points to. It also assumes you have seen the 'a syntax from the previous chapter.
Why elision exists
Every reference has a lifetime, but you rarely write one. The compiler fills in lifetimes for you when the answer is predictable. This is called lifetime elision. Elision is not inference. The compiler applies three fixed rules to function signatures. If they produce a complete signature, you may omit the annotations. If they leave any output lifetime undetermined, you get an error and must write the lifetimes yourself.
The three rules
The compiler counts lifetime positions in the parameters (input) and in the return type (output).
- Each elided lifetime in the parameters becomes its own distinct lifetime parameter.
- If there is exactly one input lifetime, it is assigned to every elided output lifetime.
- If one of the parameters is
&selfor&mut self, the lifetime ofselfis assigned to every elided output lifetime.
Rule 2 in action
first_word takes one reference and returns one reference, so rule 2 applies.
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let sentence = String::from("borrowing is useful");
let word = first_word(&sentence);
println!("{word}");
}The compiler reads the signature as fn first_word<'a>(s: &'a str) -> &'a str. The result is valid only as long as sentence is.
Rule 3 in action
With a method, self wins. The result below borrows from the struct, not from other, and the compiler assumes this without being told.
struct Parser {
text: String,
}
impl Parser {
fn first_word(&self, _other: &str) -> &str {
self.text.split_whitespace().next().unwrap_or("")
}
}
fn main() {
let p = Parser { text: String::from("hello world") };
let w = p.first_word("ignored");
println!("{w}");
}This works because the body returns data from self. If the body returned _other instead, the compiler would report a lifetime mismatch, because rule 3 tied the output to self. In that case you would annotate the signature by hand.
When the rules fail
Two reference parameters and no self leave rule 2 and rule 3 with nothing to apply. The following code does not compile:
fn longest(x: &str, y: &str) -> &str {
if x.len() >= y.len() { x } else { y }
}The compiler reports error E0106, "missing lifetime specifier". Rule 1 gives x and y separate lifetimes, but nothing says which one the result comes from. You fix this by naming the relationship:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}
fn main() {
let a = String::from("apple");
let b = String::from("fig");
println!("{}", longest(&a, &b));
}Common mistakes
- Expecting elision to look at the function body. It reads only the signature, so a body that returns a different reference than the rules assume is rejected.
- Adding
'aeverywhere "to be safe". Extra annotations that restate what elision already does add noise. They can also over-constrain a signature when you reuse one'afor unrelated parameters. - Forgetting that elision applies to return types only when the output has a lifetime position. A function returning
Stringneeds no lifetime reasoning at all.
Exercise
Does fn pick(a: &str, b: &str, flag: bool) -> &str compile without lifetime annotations? Explain using the three rules, then show a signature that fixes it if the result always comes from a.
Show answer
It does not compile. Rule 1 gives a and b separate lifetimes, rule 2 fails because there are two input lifetimes, and rule 3 fails because there is no self. The compiler reports E0106. A fix is fn pick<'a>(a: &'a str, _b: &str, flag: bool) -> &'a str. Only a shares a lifetime with the result, so b can be borrowed for a shorter time.