Lifetime elision rules help Rust understand how long references live without you writing extra code. This makes your code simpler and easier to read.
Lifetime elision rules in Rust
fn function_name(&self, param: &Type) -> &Type {
// function body
}Rust applies three main lifetime elision rules automatically.
You only need to write lifetime annotations if Rust cannot figure them out from these rules.
fn first_word(s: &str) -> &str {
// returns a slice of the input string
}fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }
impl<'a> ImportantExcerpt<'a> { fn level(&self) -> i32 { 3 } }
This program shows a struct holding a reference with a lifetime. The method uses lifetime elision rules so we don't write lifetimes on &self, the parameter, or the return type.
struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { // Method with elided lifetimes fn announce_and_return_part(&self, announcement: &str) -> &str { println!("Announcement: {}", announcement); self.part } } fn main() { let text = String::from("Rust is awesome!"); let excerpt = ImportantExcerpt { part: &text[0..4] }; let announcement = "Here is an important part:"; let result = excerpt.announce_and_return_part(announcement); println!("Returned part: {}", result); }
Time complexity: Lifetime elision does not affect runtime; it is a compile-time feature.
Space complexity: No impact on memory usage.
Common mistake: Expecting Rust to always guess lifetimes; sometimes you must write them explicitly.
When to use: Use elision to keep code clean, but add explicit lifetimes when Rust cannot infer them.
Lifetime elision rules let Rust fill in lifetimes automatically in common cases.
There are three main rules that Rust follows to guess lifetimes.
Use explicit lifetimes only when Rust cannot figure them out on its own.