C.W.K.
Stream
Lesson 05 of 05 · published

Lifetime Elision & 'static

~11 min · lifetimes, elision, static

Level 0Rust Curious
0 XP0/80 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete

If lifetimes are everywhere, why have you written almost none? Because the compiler applies elision rules — a set of defaults that fill in the obvious cases so you don't have to.

The three elision rules

One: each reference parameter gets its own lifetime. Two: if there's exactly one input lifetime, it's assigned to all outputs. Three: if there's a &self parameter (a method), its lifetime is assigned to all outputs. These three cover the overwhelming majority of functions — which is why fn first_word(s: &str) -> &str needs no annotation: rule two assigns the single input's lifetime to the output.

When elision can't decide

The longest function fails elision because it has two input lifetimes and rule two doesn't apply — the compiler can't guess which one the output borrows from. That's the precise gap where you step in and annotate. Elision handles the obvious; you handle the ambiguous.

Try writing it without annotations first. Thanks to elision, most reference-returning functions just compile. Only reach for explicit 'a when the compiler tells you it can't infer the relationship — let it ask before you annotate.

The special lifetime: 'static

'static means 'valid for the entire program.' String literals are &'static str — baked into the binary and never freed. It's a real, useful lifetime, but beginners sometimes slap 'static on things to silence errors, which usually masks a deeper ownership problem. Use it when the data truly lives forever, not as an error-silencer.

Code

Elision: why most functions need no annotation·rust
// No 'a needed: one input lifetime, rule 2 assigns it to the output.
fn first_word(s: &str) -> &str {
    s.split(' ').next().unwrap_or("")
}

// 'static: lives for the whole program (string literals are &'static str)
fn motto() -> &'static str {
    "fearless"
}

fn main() {
    println!("{}", first_word("hello world"));
    println!("{}", motto());
}

External links

Exercise

Write three functions: one taking a single &str and returning a &str (elided), one method on a struct returning &self's field (elided by rule 3), and one returning a &'static str literal. For each, explain which elision rule (or 'static) applies.
Hint
Single input -> rule 2. &self method -> rule 3. A literal -> 'static. If you can name the rule, you understand why the annotation is or isn't needed.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Ttoriwarm

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.