Sub topic 13
Lifetime Elision Rules
This chapter assumes you can write a function with a lifetime parameter such as longest<'a>, and that you know shared and mutable references. It explains why many functions need no lifetime annotations, and when the compiler still asks for them.
What elision is
Lifetime elision is a set of fixed rules the compiler applies to fill in lifetimes you left out. It is not inference. If the rules do not produce a complete answer, the compiler reports an error and asks you to write the lifetimes yourself.
Earlier, first_word(s: &str) -> &str compiled with no 'a at all. The compiler read it as this:
fn first_word<'a>(s: &'a str) -> &'a str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
println!("{}", first_word("hello world"));
}The three rules
The compiler applies these rules in order to a function signature. Input lifetimes are on parameters. Output lifetimes are on the return type.
- Each reference parameter that has no lifetime gets its own distinct lifetime.
- If there is exactly one input lifetime, it is assigned to every output lifetime.
- If one of the parameters is
&selfor&mut self, the lifetime ofselfis assigned to every output lifetime.
If any output lifetime is still unknown after these rules, compilation fails.
Where elision succeeds and fails
| Signature | Result |
|---|---|
| `fn len(s: &str) -> usize` | No output reference, so nothing to resolve. |
| `fn first_word(s: &str) -> &str` | Rule 2 applies, one input. |
| `fn get(&self, i: usize) -> &str` | Rule 3 applies, output tied to `self`. |
| `fn longest(x: &str, y: &str) -> &str` | Error. Two inputs, no `self`. |
The last case fails because the compiler cannot tell whether the result borrows from x or y. Your annotation answers that question, which is why longest<'a> ties both inputs to the output.
Elision with methods
Rule 3 is why methods rarely need annotations. The returned reference is assumed to borrow from self, not from the other arguments.
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn announce(&self, note: &str) -> &str {
println!("Note: {note}");
self.part
}
}
fn main() {
let text = String::from("Call me Ishmael. Some years ago...");
let e = Excerpt { part: text.split('.').next().unwrap() };
println!("{}", e.announce("reading"));
}Here announce returns a value tied to &self, even though note is also a reference. If you wanted the result to borrow from note, you would have to write that explicitly.
Common errors
- "missing lifetime specifier": the rules left an output lifetime unresolved, usually two reference parameters and a reference return. Add a named lifetime.
- Wrong assumption under rule 3: the method compiles, but the result is tied to
selfwhen you meant another argument. This shows up as borrow errors at the call site, not at the definition. - Returning a reference to a local: elision cannot fix this. The data would still be dropped, which is the dangling reference problem from the earlier chapter.
Exercise
Does fn pick(a: &str, b: &str) -> &str compile? What about fn pick(&self, b: &str) -> &str inside an impl block? Explain using the rules.
Show answer
The first does not compile. Rule 1 gives a and b separate lifetimes, rule 2 needs exactly one input lifetime, and there is no self for rule 3, so the output lifetime is unknown. The second compiles because rule 3 ties the output to the lifetime of &self.