Lifetimes
Lifetime annotations, the elision rules, structs that hold references, `'static`, and variance at the senior level.
12 questions
JuniorTheoryCommonWhat does the program print?
What does the program print?
llo
Open full question →Common mistakes
- ✗Expecting E0106 because
tailhas two parameters: elision rules count only references, andn: usizeis not one, so rule 2 givess's lifetime to the result. - ✗Reading
&s[n..]as the firstnbytes: the rangen..starts at indexnand runs to the end.
Follow-up questions
- →What does
taillook like with the lifetime the compiler fills in written out? - →Why would
fn pick(x: &str, y: &str) -> &strnot compile without annotations?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
long stringbecauseresultwould point ata: the compiler checks only the signature, which lets the result borrow fromb, so it may not outliveb(E0597). - ✗Expecting the shorter string
xyz:'abounds how long the result stays valid, not which argumentlongestreturns.
Follow-up questions
- →How would you move one line so that the program compiles and prints
long string? - →How would the signature change if
longestalways returnedx?
MiddleTheoryCommonWhat are the three lifetime elision rules, and when must a signature name lifetimes?
What are the three lifetime elision rules, and when must a signature name lifetimes?
1) Each reference parameter gets its own lifetime. 2) A single input lifetime goes to every output. 3) If an input is &self or &mut self, outputs get its lifetime. fn first(s: &str) -> &str uses rule 2; an output no rule covers is E0106.
Common mistakes
- ✗Believing elision infers lifetimes from the function body rather than from the signature
- ✗Thinking two reference inputs share one lifetime, so the output is covered
- ✗Trusting rule 3 when a method may return a parameter rather than data owned by
self
Follow-up questions
- →Why does
fn name_or(&self, fallback: &str) -> &strfail when it returnsfallback? - →Which rule applies to
fn parse(input: &str, n: usize) -> &str, and why?
MiddleTheoryCommonDoes longest<'a>(x: &'a str, y: &'a str) -> &'a str need inputs that live equally long?
Does longest<'a>(x: &'a str, y: &'a str) -> &'a str need inputs that live equally long?
No. At each call the compiler picks 'a as a region where both borrows are valid, at most their overlap: a longer-lived reference may be used for a shorter region. The result is valid only within 'a, so it can't outlive the shorter input.
Common mistakes
- ✗Reading a shared
'aas a demand that both arguments live equally long - ✗Expecting the result to live as long as whichever argument is returned at run time
- ✗Putting one
'aon every reference when the result borrows from one input only
Follow-up questions
- →How would you write the signature if the result always borrowed from
xalone? - →Which property of
&'a Tlets a longer-lived reference be passed where&'a stris expected?
MiddleTheoryCommonHow does &'static T differ from the bound T: 'static, and why does thread::spawn need it?
How does &'static T differ from the bound T: 'static, and why does thread::spawn need it?
&'static T points to data that lives until exit: literals, statics, Box::leak. T: 'static means the type holds no shorter borrow, so an owned String qualifies yet drops as usual. thread::spawn needs it: a thread may outlive its caller.
Common mistakes
- ✗Reading
T: 'staticas "lives for the whole program" rather than "holds no short-lived borrows" - ✗Believing
'staticdata must sit in the binary, forgettingBox::leakand owned types - ✗Fixing E0373 from
thread::spawnwith'staticannotations instead ofmoveorArc
Follow-up questions
- →Why does
Box<dyn Error>meanBox<dyn Error + 'static>, and when does that bite? - →How does
std::thread::scopelet threads borrow local variables without'static?
MiddleTheoryCommonWhy does a struct holding a reference need a lifetime, and what does Parser<'a> promise?
Why does a struct holding a reference need a lifetime, and what does Parser<'a> promise?
A &str field must say whose data it borrows, hence 'a: struct Parser<'a> { input: &'a str } promises no Parser outlives that input. Each impl names it, as impl<'a> Parser<'a> or Parser<'_>; 'a caps the struct's life, not sets it.
Common mistakes
- ✗Thinking the lifetime parameter keeps the borrowed data alive
- ✗Writing a getter as
-> &str, which ties the result to the struct instead of to the input - ✗Holding
&strin a struct that must outlive its input, where aStringfield fits better
Follow-up questions
- →Why does a getter
fn input(&self) -> &strgive a shorter-lived result than-> &'a str? - →When is
impl Parser<'_>enough instead ofimpl<'a> Parser<'a>?
MiddleTheoryCommonWhat is a lifetime in Rust, what does 'a express, and when must you write one?
What is a lifetime in Rust, what does 'a express, and when must you write one?
A lifetime is the region of code where a reference is used; the value must stay alive across it. 'a names a region in a signature to link references and extends nothing. It is needed when a signature alone can't show what a result borrows from.
Common mistakes
- ✗Thinking an annotation makes a value live longer instead of describing a link between references
- ✗Equating a reference's lifetime with its variable's lexical scope rather than with its uses
- ✗Believing lifetimes exist at run time or cost anything in the compiled program
Follow-up questions
- →Why does the compiler check a call against the callee's signature and never its body?
- →Why do lifetime annotations almost never appear inside a function body?
JuniorDebuggingOccasionalFix a function that returns &'static str built from a String (E0515)
Fix a function that returns &'static str built from a String (E0515)
&'static str promises data valid until the program ends. Literals like "OK" qualify, but text is a local String freed on return, so &text would dangle (E0515). Return an owned String or a Cow<'static, str>.
Common mistakes
- ✗Thinking a
'staticannotation makes a local value live longer - ✗Dropping
'staticfor-> &str, which fails with E0106: there is no input to borrow from - ✗Returning
text.as_str(), which still borrows the localString
Follow-up questions
- →Why does a string literal such as
"OK"have the type&'static str? - →When is the clone-on-write type
Cow<'static, str>worth it over a plainString?
MiddleDebuggingOccasionalFix a signature that ties the returned &str to the wrong input
Fix a signature that ties the returned &str to the wrong input
The result is a slice of s (split yields parts of s), so it borrows from s, not sep: write fn first_word<'a>(s: &'a str, sep: &str) -> &'a str. Adding 'a: 'b or one shared 'a compiles the body but still ties word to sep (E0597).
Common mistakes
- ✗Applying the compiler's
'a: 'bhint, which fixes the body but keepswordtied tosep - ✗Putting one
'aon every reference, which makessepoutlive every use of the result - ✗Annotating the separator even though the result never borrows from it
Follow-up questions
- →Why can an
impl Iterator<Item = &'a str>result in edition 2024 stay tied to an unrelated&str? - →Why is the compiler's suggested bound
'a: 'bnot the fix this caller needs?
SeniorTheoryOccasionalWhat does the higher-ranked bound for<'a> Fn(&'a str) -> &'a str mean, and where does it appear?
What does the higher-ranked bound for<'a> Fn(&'a str) -> &'a str mean, and where does it appear?
The closure must accept any lifetime, not one the caller picks, so the function can pass it borrows of its own locals. F: Fn(&str) -> &str means this by elision; a closure stored in a let first may fix one lifetime: not general enough.
Common mistakes
- ✗Believing
F: Fn(&str) -> &strfixes one caller-chosen lifetime, sofor<'a>must always be spelled out - ✗Reading
for<'a>as'static, as if the argument had to live forever - ✗Storing a closure in a
letbefore passing it, which can lose the higher-ranked signature
Follow-up questions
- →Why does
let f = |s: &str| s;fail to compile while the same closure passed inline works? - →How does a helper
fn constrain<F: Fn(&str) -> &str>(f: F) -> Ffix a stored closure?
SeniorDesignOccasionalA service reads a 5 MB configuration file into a String once at startup and parses it into about 200,000 key–value entries. The author wants one value to own both: struct Config { text: String, entries: Vec<(&str, &str)> }, where every key and value is a slice of text, so that Config::load(path) can return it and the application can keep it in a global cache shared by worker threads. Adding a lifetime parameter, Config<'a> with entries: Vec<(&'a str, &'a str)>, does not help: building it inside load fails with error[E0505]: cannot move out of `text` because it is borrowed. Constraints: no per-entry copy of the text, lookups by key on the hot path, no unsafe in application code, and the type must be Send + Sync + 'static to live in the cache. Why is this struct hard to express in safe Rust, and how would you restructure it?
A service reads a 5 MB configuration file into a String once at startup and parses it into about 200,000 key–value entries. The author wants one value to own both: struct Config { text: String, entries: Vec<(&str, &str)> }, where every key and value is a slice of text, so that Config::load(path) can return it and the application can keep it in a global cache shared by worker threads. Adding a lifetime parameter, Config<'a> with entries: Vec<(&'a str, &'a str)>, does not help: building it inside load fails with error[E0505]: cannot move out of `text` because it is borrowed. Constraints: no per-entry copy of the text, lookups by key on the hot path, no unsafe in application code, and the type must be Send + Sync + 'static to live in the cache. Why is this struct hard to express in safe Rust, and how would you restructure it?
Safe Rust cannot name the lifetime of a sibling field, and a borrowed text cannot be moved in. Store Range<usize> offsets into text and slice on lookup, split an owner from a borrowed view, or use the self_cell crate; Pin + unsafe last.
Common mistakes
- ✗Expecting
BoxorPinalone to make the borrow checker accept a self-reference - ✗Copying every entry into its own
String, which breaks the no-copy constraint, instead of storing offsets - ✗Reaching for raw pointers and
unsafebefore trying offsets or an owner–view split
Follow-up questions
- →What does an offset-based index give up compared with
&strfields, and how do you guard it? - →How do self-referencing crates like
self_cellkeep the borrow sound withoutPin?
SeniorTheoryOccasionalWhat are co-, contra- and invariance over lifetimes, and why is &'a mut T invariant in T?
What are co-, contra- and invariance over lifetimes, and why is &'a mut T invariant in T?
Covariant types accept a longer lifetime for a shorter (&'static str as &'a str), contravariant ones the reverse (fn(&'a str)), invariant ones neither. &mut T is invariant in T: a write could put a short-lived reference in a 'static slot.
Common mistakes
- ✗Swapping the direction, as if a short-lived reference could stand in for a
'staticone - ✗Explaining invariance by the exclusivity of
&mutrather than by writes through it - ✗Writing
&'a mut Vec<&'a str>, which keeps the vector borrowed for the rest of its life
Follow-up questions
- →Why does
fn add<'a>(v: &'a mut Vec<&'a str>, w: &'a str)block a second call on the same vector? - →Why is
Cell<&'a str>invariant although its type has no&mutin it?