In this lesson, you will learn how the Rust compiler uses Lifetime Elision Rules to automatically fill in lifetime annotations so you don't have to write them manually.
The Problem of Verbosity
In our previous lesson, we learned that Rust requires us to tell the compiler how long references stay valid to ensure memory safety. Explicitly writing out every 'a (like fn longest<'a>(x: &'a str, y: &'a str) -> &'a str) can make code look cluttered.
Fortunately, the Rust team discovered that programmers write the same patterns over and over. They codified these patterns into Lifetime Elision Rules. If your function signature matches these patterns, the compiler infers the lifetimes for you automatically.
The Three Rules
The compiler applies these three rules in order. If it still can’t figure out the lifetimes after applying these, it will stop and demand that you write them explicitly.
- Input Rules: Each reference parameter gets its own lifetime parameter.
fn foo(x: &i32)becomesfn foo<'a>(x: &'a i32).fn bar(x: &i32, y: &i32)becomesfn bar<'a, 'b>(x: &'a i32, y: &'b i32).
- Single Input Rule: If there is exactly one input lifetime parameter (from the first rule), that lifetime is assigned to all output lifetime parameters.
fn get_val(x: &i32) -> &i32becomesfn get_val<'a>(x: &'a i32) -> &'a i32.
- Method Rule: If there are multiple input lifetime parameters, but one of them is
&selfor&mut self(because this is a method), the lifetime ofselfis assigned to all output lifetime parameters.
Why this matters
Consider this common method:
impl MyStruct {
fn get_data(&self) -> &str {
&self.data
}
}
Because of the Method Rule, the compiler knows the return value must live as long as self. You don't have to write 'a anywhere! The rules handle the most common scenarios, keeping your code readable while maintaining strict memory safety.
Key Takeaway: Lifetime Elision Rules allow the compiler to automatically infer lifetimes based on common patterns, meaning you only need to write explicit annotations when the compiler cannot definitively determine the relationship between references.