Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Lifetimes Explained: Annotations, Struct References, and Elision

Lifetimes describe relationships, not durations. The three elision rules, what 'static really means, and the two errors no annotation can fix.

~4 min readRust
#Rust#Lifetimes#Syntax
3D illustration of overlapping reference timeline bars bound by glowing scope markers

Quick Summary

A lifetime annotation does not extend a value's life and does not create anything at runtime. 'a is a compile-time name for "some region of code", and an annotation only records which references must be valid at the same time. All generic lifetime parameters are erased during compilation; the program that runs is identical either way.

Most of the time you write no lifetimes at all, because elision fills them in. Three rules do the work: each input reference gets its own lifetime; if there is exactly one input lifetime, all elided outputs get it; and if a method takes &self or &mut self, elided outputs get the lifetime of self. Everything else needs an explicit parameter, and the compiler error E0106 missing lifetime specifier is literally telling you the elision rules ran out.

Two failures account for most of the pain. Returning a reference to a local (E0515) is not solvable with annotations — the data must be owned by the caller. And borrows of temporaries (E0716) need a let binding so the owner lives long enough. 'static is widely misunderstood: it means "valid for the entire program", so it fits string literals and leaked data, and in a trait bound T: 'static only means "contains no borrowed data", not "lives forever".

Basic syntax and query signatures

rust
// One lifetime tying two inputs to the output fn longest<'a>(a: &'a str, b: &'a str) -> &'a str { if a.len() >= b.len() { a } else { b } } // Distinct lifetimes: the output is only tied to the first fn first_of<'a, 'b>(a: &'a str, b: &'b str) -> &'a str { a } // A struct that borrows struct Token<'a> { text: &'a str } impl<'a> Token<'a> { fn text(&self) -> &'a str { self.text } // elided output tied to 'a, not &self fn len(&self) -> usize { self.text.len() } } // Placeholder: let the compiler infer fn wrap(s: &str) -> Token<'_> { Token { text: s } } // 'static as a bound: no borrowed data inside fn spawn_it<F>(f: F) where F: Fn() + Send + 'static { /* ... */ } // Only a literal really is &'static const GREETING: &str = "hello";

Elided and explicit forms are equivalent; knowing the rules lets you read both:

rust
fn elided(s: &str) -> &str { s } // one input -> output gets it fn explicit<'a>(s: &'a str) -> &'a str { s } impl Foo { fn get(&self) -> &str { "" } // output tied to &self }

Key comparison table

SituationAnnotation neededExample
One input reference, one outputNofn f(s: &str) -> &str
&self method returning a referenceNofn name(&self) -> &str
Two input references, one outputYesfn longest<'a>(&'a str, &'a str) -> &'a str
Struct holding a referenceYesstruct T<'a> { s: &'a str }
Returning a reference to a localImpossibleReturn the owned value
No references in or outNot neededfn f(x: u32) -> u32
Trait object with referencesYes, often Box<dyn Trait + 'a>Explicit bound
ErrorMeaningCorrect response
E0106 missing lifetime specifierElision could not fill an outputAdd 'a and tie inputs to it
E0515 returns value referencing local variableReturning a reference to owned localReturn owned data
E0597 borrowed value does not live long enoughOwner dropped before the borrow endsMove the owner up, or shorten the borrow
E0621 explicit lifetime requiredA bound is missing on a typeAdd T: 'a or an explicit parameter
E0716 temporary value dropped while borrowedBorrowed a temporarylet tmp = ...; &tmp
E0495 cannot infer an appropriate lifetimeAmbiguous relationshipMake the relationship explicit

Practical edge cases and deep dives

1. A struct that borrows forces every use to carry the lifetime

rust
struct Parser<'a> { input: &'a str, pos: usize } impl<'a> Parser<'a> { fn new(input: &'a str) -> Self { Parser { input, pos: 0 } } fn rest(&self) -> &'a str { &self.input[self.pos..] } } fn parse(input: &str) -> usize { let p = Parser::new(input); // borrows input, so input must outlive p p.rest().len() }

The alternative is to own the data — String inside the struct — and the trade-off is real: borrowing avoids an allocation but pushes the lifetime parameter into every type that stores the parser.

2. Returning a reference to a computed value never works

rust
// E0515: returns a value referencing local variable // fn shout(s: &str) -> &str { &s.to_uppercase() } fn shout(s: &str) -> String { s.to_uppercase() } // correct: ownership moves out fn shout_into(s: &str, out: &mut String) { out.clear(); out.push_str(&s.to_uppercase()); }

No annotation can fix this, because the annotated lifetime would have to include a value that is dropped at the end of the function. The compiler message is the whole answer: return an owned value, or write into a caller-provided buffer.

3. 'static in a bound is not "lives forever"

rust
fn takes_static<T: 'static>(x: T) {} takes_static(5); // OK: no references at all takes_static(String::from("owned")); // OK takes_static("literal"); // OK: &'static str // let s = String::from("x"); // takes_static(s.as_str()); // error: &s is not 'static // Box::leak is how you turn owned data into &'static (and never free it) let leaked: &'static str = Box::leak(String::from("x").into_boxed_str());

T: 'static means "T contains no non-static references". It is exactly the bound that std::thread::spawn needs because the thread may outlive the current scope.

4. Temporaries: the let binding that fixes E0716

rust
// let r = &String::from("temp").as_str(); // E0716: temporary dropped while borrowed let owned = String::from("temp"); let r = owned.as_str(); // fine: owner lives in a binding // The same trap with method chains let v = vec![1, 2, 3]; // let it = v.iter().filter(|x| **x > 1); // v is borrowed by a temporary? let it: Vec<&i32> = v.iter().filter(|x| **x > 1).collect();

Lifetime extension applies to let x = &expr; in simple forms, but not through function calls in a chain. When the error appears, the fastest fix is to give the owner a name.

5. Higher-ranked trait bounds for closures over references

A closure that takes a reference needs a bound that works for any lifetime, not a single named one.

rust
fn apply<F>(f: F, s: &str) -> usize where F: for<'a> Fn(&'a str) -> usize // works for every 'a { f(s) } let n = apply(|x| x.len(), "hello");

Without for<'a>, the compiler tries to pick one concrete lifetime and the closure ends up too restrictive. Most everyday code elides this because Fn(&str) -> usize already desugars to a higher-ranked bound; you only see the syntax when you nest it inside another generic type.

6. Lifetimes in impl blocks and trait objects

rust
struct Wrap<'a, T: 'a> { inner: &'a T } impl<'a, T> Wrap<'a, T> { fn get(&self) -> &'a T { self.inner } } trait Source<'a> { fn next(&mut self) -> Option<&'a str>; } let src: Box<dyn Source<'static> + '_> = unimplemented!();

When a generic type carries borrowed data, the bound T: 'a is required, otherwise the struct cannot be instantiated. E0621 explicit lifetime required is the message that points this out.

7. Self-referential structs: the case lifetimes cannot solve

rust
// Cannot express: the struct borrows its own field // struct SelfRef { data: String, slice: &'? str } // Options: hold indices, own the pieces separately, or use a crate struct Owned { data: String } impl Owned { fn head(&self) -> &str { &self.data[..1] } // compute on demand } // Or a small arena / ouroboros / rental-style crate for the genuinely needed case

A struct that contains both a String and a &str into it can never be written with lifetimes, because moving the struct would invalidate the reference. This is the boundary where you stop modelling with lifetimes and change the data layout instead.

Common mistakes and runtime errors

ErrorCauseFix
E0106 missing lifetime specifierTwo inputs, one elided outputName the lifetime and tie both inputs
E0515 returns value referencing localReturning & to owned localReturn the value
E0597 does not live long enoughOwner dropped firstHoist the owner out of the inner scope
E0621 explicit lifetime requiredMissing T: 'a boundAdd the bound or parameter
E0716 temporary dropped while borrowedBorrowed a temporary from a chainBind the owner to a let
E0495 cannot infer lifetimeAmbiguous relationshipMake the tie explicit
dyn Trait needs a lifetimeDefault object bound is 'staticBox<dyn Trait + 'a>
'static bound rejects &str&s is shorter than 'staticOwn the data (to_string) or leak it
Two-input function returns the wrong referenceBoth inputs forced to one lifetimeSplit into 'a and 'b
Struct works, method returning field does notElided output tied to &selfReturn with the struct's lifetime 'a
Borrow lives to end of blockPre-NLL mental modelBorrows end at last use in modern Rust

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.