patternrustModeratepending
Rust lifetime elision rules and common patterns
Viewed 0 times
lifetimeelisionborrowingstaticreference
Problem
Confusion about when Rust requires explicit lifetime annotations and when they can be elided.
Solution
Rust applies three lifetime elision rules automatically:
Rule of thumb: if the compiler asks for lifetimes, the borrow checker needs to know which input lifetime connects to the output.
// Rule 1: Each reference parameter gets its own lifetime
// fn foo(x: &str, y: &str) -> fn foo<'a, 'b>(x: &'a str, y: &'b str)
// Rule 2: If exactly one input lifetime, it's used for all outputs
fn first_word(s: &str) -> &str { ... }
// Equivalent to: fn first_word<'a>(s: &'a str) -> &'a str
// Rule 3: If &self or &mut self, self's lifetime is used for outputs
impl MyStruct {
fn name(&self) -> &str { &self.name }
// Equivalent to: fn name<'a>(&'a self) -> &'a str
}
// When you NEED explicit lifetimes:
// Multiple references in, reference out
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
// Struct holding references
struct Excerpt<'a> {
text: &'a str,
}
// Static lifetime (lives for entire program)
fn constant() -> &'static str {
"I live forever"
}Rule of thumb: if the compiler asks for lifetimes, the borrow checker needs to know which input lifetime connects to the output.
Why
Lifetime elision rules handle the common cases automatically. Understanding the rules helps you know when explicit annotations are needed and what they mean.
Context
Rust code with references, especially functions returning references
Revisions (0)
No revisions yet.