Lifetime Elision Rules
In this page:
Elision Rule: One Input, One Output
When a function has exactly one reference parameter and returns a reference, the compiler automatically assumes the output lifetime matches the input's, with no annotation needed.
Example: Elision Rule: One Input, One Output
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
fn main() {
println!("{}", first_word("hello world"));
}
Login to try C/C++/Java/PHP code in the editor
Elision in Methods Using self
For methods taking &self, the elision rules assign the lifetime of self to any elided reference in the return type, which is why so many getter-style methods need no explicit lifetime syntax.
Example: Elision in Methods Using self
struct Container {
text: String,
}
impl Container {
fn get_text(&self) -> &str {
&self.text
}
}
fn main() {
let c = Container { text: String::from("elided lifetime works here") };
println!("{}", c.get_text());
}
Login to try C/C++/Java/PHP code in the editor
When Elision Is Not Enough
With more than one reference parameter and no self, the compiler cannot guess which input the output relates to, so an explicit lifetime annotation becomes necessary.
Example: When Elision Is Not Enough
fn pick_longer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() > b.len() { a } else { b }
}
fn main() {
println!("{}", pick_longer("short", "much longer"));
}
Login to try C/C++/Java/PHP code in the editor
Elision Reduces Boilerplate
Because of these rules, the vast majority of everyday Rust functions involving references need zero explicit lifetime syntax, and annotations only appear when the relationship is genuinely ambiguous.
Example: Elision Reduces Boilerplate
fn trim_and_return(s: &str) -> &str {
s.trim()
}
fn main() {
println!("[{}]", trim_and_return(" padded "));
}
Login to try C/C++/Java/PHP code in the editor
- Writing out explicit lifetime annotations for simple functions the elision rules already handle automatically, adding unnecessary noise.
- Assuming elision applies to every function shape -- it only covers a specific set of common patterns; anything more complex still needs explicit annotations.
- Forgetting that a method taking
&selfusesself's lifetime for any elided return reference, by the third elision rule.
- Lifetime elision rules let the compiler infer lifetimes for common, simple function signatures without explicit annotations.
- Rule one: each reference parameter gets its own inferred lifetime.
- Rule two: if there is exactly one input lifetime, it is assigned to all elided output lifetimes.
- Rule three: for methods, the lifetime of
&selfis assigned to elided output lifetimes.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: