Lifetime elision
Lifetime elision is the set of rules that fill in 'a for you in common function signatures. One input reference and an output reference are assumed to share a lifetime.
Detailed Explanation
Writing 'a on every function would be noise. The compiler applies three rules to function signatures (and a similar set to impl headers). If they produce a unique answer, you omit the lifetimes. If they do not, you write them.
Rule one: each elided input lifetime becomes its own parameter. fn f(x: &i32, y: &i32) is fn f<'a, 'b>(x: &'a i32, y: &'b i32). Rule two: if there is exactly one input lifetime, it is assigned to every elided output lifetime. fn f(x: &str) -> &str is fn f<'a>(x: &'a str) -> &'a str. Rule three: if there are multiple input lifetimes but one of them is &self or &mut self, that lifetime is assigned to every elided output. Methods that return a reference to a field rely on this.
These rules do not apply to longest(a: &str, b: &str) -> &str. Two inputs, no self, so the output lifetime is unknown. The compiler asks you to write 'a. They do not apply to structs; a field &str always needs <'a> on the struct.
Elision is not inference from the function body. The body must match the signature after elision. If you return the second argument while elision tied the output to the first, that is an error. The signature is the contract.
When you rely on elision: getters, as_str, most methods. When you write lifetimes: two or more borrowed inputs, or a struct that stores a borrow. When elision surprises you: look at the method-self rule; it is the one people forget exists.
Code Examples
struct Session {
token: String,
}
impl Session {
// elision: output borrows from `&self`
fn token(&self) -> &str {
&self.token
}
}
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let s = Session { token: "abc".into() };
println!("{}", s.token()); // prints: abc
println!("{}", first_word("ada lovelace")); // prints: ada
}Common Gotchas
Two borrowed arguments and a borrowed return need an explicit lifetime
Elision will not pick. Annotate or return an owned value.
Elision does not read the body
A wrong assumption in the signature is a compile error inside the function, not a silent swap of arguments.
`&self` methods get the third rule
Returning a reference from a method is usually elided. Returning a reference to a parameter that is not `self` is not.
Async blocks and closures have pickier elision
If a closure captures a reference and is `'static` (spawned), elision will not save you. Own the data.