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.

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
// 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:
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
| Situation | Annotation needed | Example |
|---|---|---|
| One input reference, one output | No | fn f(s: &str) -> &str |
&self method returning a reference | No | fn name(&self) -> &str |
| Two input references, one output | Yes | fn longest<'a>(&'a str, &'a str) -> &'a str |
| Struct holding a reference | Yes | struct T<'a> { s: &'a str } |
| Returning a reference to a local | Impossible | Return the owned value |
| No references in or out | Not needed | fn f(x: u32) -> u32 |
| Trait object with references | Yes, often Box<dyn Trait + 'a> | Explicit bound |
| Error | Meaning | Correct response |
|---|---|---|
E0106 missing lifetime specifier | Elision could not fill an output | Add 'a and tie inputs to it |
E0515 returns value referencing local variable | Returning a reference to owned local | Return owned data |
E0597 borrowed value does not live long enough | Owner dropped before the borrow ends | Move the owner up, or shorten the borrow |
E0621 explicit lifetime required | A bound is missing on a type | Add T: 'a or an explicit parameter |
E0716 temporary value dropped while borrowed | Borrowed a temporary | let tmp = ...; &tmp |
E0495 cannot infer an appropriate lifetime | Ambiguous relationship | Make the relationship explicit |
Practical edge cases and deep dives
1. A struct that borrows forces every use to carry the lifetime
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
// 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"
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
// 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.
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
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
// 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 caseA 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
| Error | Cause | Fix |
|---|---|---|
E0106 missing lifetime specifier | Two inputs, one elided output | Name the lifetime and tie both inputs |
E0515 returns value referencing local | Returning & to owned local | Return the value |
E0597 does not live long enough | Owner dropped first | Hoist the owner out of the inner scope |
E0621 explicit lifetime required | Missing T: 'a bound | Add the bound or parameter |
E0716 temporary dropped while borrowed | Borrowed a temporary from a chain | Bind the owner to a let |
E0495 cannot infer lifetime | Ambiguous relationship | Make the tie explicit |
dyn Trait needs a lifetime | Default object bound is 'static | Box<dyn Trait + 'a> |
'static bound rejects &str | &s is shorter than 'static | Own the data (to_string) or leak it |
| Two-input function returns the wrong reference | Both inputs forced to one lifetime | Split into 'a and 'b |
| Struct works, method returning field does not | Elided output tied to &self | Return with the struct's lifetime 'a |
| Borrow lives to end of block | Pre-NLL mental model | Borrows end at last use in modern Rust |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.