skip to content

Lifetimes

Lifetimes name how long a borrow must stay valid so the compiler can rule out dangling references. Interviewers test annotations, elision, structs holding references and variance.

on this pageshow

explore

questions

29

In Rust, why does a config lookup `fn pick(primary: &str, fallback: &str) -> &str` need a lifetime parameter, and what does `'a` promise?

level: juniorimportance: must knowfreq 80%

answer

  1. two inputs, one output borrow
  2. signature must name the source
  3. same 'a on all three
  4. result valid for the shorter borrow

basics

~20 s

The returned &str may borrow from either argument, and the bare signature does not say which, so rustc stops with E0106. Writing 'a on both inputs and the output promises the result is valid only while both borrows are.

solid answer

~40 s

The body returns `primary` or `fallback`, chosen at run time, and rustc checks callers against the signature alone, so it needs to know which inputs the output borrows from; with two reference inputs elision cannot decide, and rustc reports `E0106: missing lifetime specifier`. Writing `fn pick<'a>(primary: &'a str, fallback: &'a str) -> &'a str` says: for some region `'a`, both arguments are valid for at least `'a`, and the result is valid for `'a`. At each call rustc picks `'a` as the overlap of the two borrows, so the result is usable only as long as the shorter-lived argument. The annotation does not keep either `String` alive; it only lets the borrow checker reject a body that returns something else and a caller that uses the result too late.

code

rust · 4 lines
rust
fn pick(primary: &str, fallback: &str) -> &str {
    if primary.is_empty() { fallback } else { primary }
}
fn main() { println!("{}", pick("", "x")); }

go deeper

for a junior

Recall that a function returning one of two borrowed inputs needs a named lifetime on both inputs and the output, and that the result is valid only while both inputs are.

for a middle

Explain how rustc picks the concrete 'a at a call as the overlap of both borrows, and why the signature, not the body, is what callers are checked against.

for a senior

Show you tie only the inputs the output can actually borrow from, and that you read E0106 and E0621 as the signature and the body disagreeing about that relation.

for a principal

Frame lifetime parameters as part of a function's public contract: a relation stated too loosely or too tightly is an API decision callers inherit, so state the honest one.

## The problem the compiler sees A function that returns a reference has to say where that reference points. In Rust, a **lifetime** is the region of the program in which a borrow must stay valid, and every reference type carries one, even when you do not write it. Take a configuration lookup that prefers an explicit value and falls back to a default: ```rust fn pick(primary: &str, fallback: &str) -> &str { if primary.is_empty() { fallback } else { primary } } ``` The returned `&str` is either `primary` or `fallback`, decided at run time. rustc checks each function body against its **signature**, and checks each call against that same signature, never by reading the other side. Nothing in this signature says which input the output borrows from, and the elision shortcuts that let you omit lifetimes in simple signatures have no single input to pick, so rustc stops: ```plaintext error[E0106]: missing lifetime specifier = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `primary` or `fallback` ``` ## What `'a` says The fix is a **generic lifetime parameter**, declared in angle brackets like a type parameter and attached to each reference it relates: ```rust fn pick<'a>(primary: &'a str, fallback: &'a str) -> &'a str { if primary.is_empty() { fallback } else { primary } } ``` Read the signature as a contract: - for some region `'a` that the compiler chooses at each call, - both arguments must be valid for at least `'a`, - and the returned `&str` is valid for `'a`, and no longer. At a call site rustc picks the concrete `'a` as the part of the program where *both* borrows are valid, so the result is usable only for the shorter of the two. The Rust Book phrases the promise as: the returned reference will be valid as long as both of the parameters are valid. A `String` and a string literal can be passed together; `'a` simply shrinks to the overlap. ## What it does not do Lifetime annotations **describe** relationships; they do not create them: 1. They do not make any `String` live longer or drop later. When a value is dropped is decided by ownership and scope alone. 2. They do not change the generated machine code; lifetimes are checked at compile time and erased before code generation. 3. They do not let the body return something unrelated to its inputs; a reference to a local still fails with its own error. What they give the borrow checker is a relation to enforce on both sides. Inside `pick`, it checks that every returned value really is valid for `'a`. At each call, it checks that the caller does not use the result after either argument stops being valid. ## Choosing which inputs to tie A signature should name only the inputs the result can actually borrow from: | Signature | What it promises | |---|---| | `fn pick<'a>(primary: &'a str, fallback: &'a str) -> &'a str` | the result may come from either input and is valid while both are | | `fn pick<'a>(primary: &'a str, fallback: &str) -> &'a str` | the result comes from `primary` only; `fallback` may be dropped right after the call | | `fn pick(primary: &str, fallback: &str) -> String` | no borrow is returned, so no lifetime parameter is needed, at the cost of an allocation | If you write the second signature but the body returns `fallback`, rustc rejects the body rather than the callers: ```plaintext error[E0621]: explicit lifetime required in the type of `fallback` ``` The signature promised something the body breaks, and the error appears where the mistake was made. ## Why the signature carries it Putting lifetimes in the signature keeps checking **local**. A caller compiles against the signature only, so editing the body of `pick` cannot silently break code in another module, and a misuse is reported against the exact borrow and the exact signature that conflict. The same applies to a method in an `impl` block: a method that returns either a field of `self` or one of its arguments declares its own `<'a>` on both. Points to carry into an interview: - two input borrows and one output borrow: say which inputs the output comes from; - the same `'a` on several inputs means "valid while all of them are"; - annotations constrain what compiles; they never extend a value's life.

  • Why does rustc not read the body of pick to work out which input the result borrows from?
    Lifetimes are part of the function's contract, like its types. Callers are checked against the signature only, so editing the body cannot silently break callers in other modules, and errors point at the exact signature and borrow that conflict instead of at a use many steps away.
  • If pick only ever returns primary, how should its signature change?
    Tie only `primary` to the output: `fn pick<'a>(primary: &'a str, fallback: &str) -> &'a str`. Callers may then drop `fallback` right after the call. If the body later tried to return `fallback`, rustc would reject the body with `E0621: explicit lifetime required in the type of fallback`.
  • A method returns either a field of self or its &str argument. What does it need?
    The same idea: declare `fn host_or<'a>(&'a self, fallback: &'a str) -> &'a str`. Left implicit, the output is tied to `&self` alone, and returning `fallback` fails with "lifetime may not live long enough".

  • The 'a makes both strings live as long as the result needs them.
  • rustc reads the function body to decide which input the result borrows from.
  • Both arguments must have exactly the same lifetime at the call site.
  • 'a names a fixed duration, such as the whole program.
  • Adding 'a changes the code rustc generates for pick.
open as a page

In Rust, what is lifetime elision, and why does `fn first_line(text: &str) -> &str` compile without writing any lifetime?

level: juniorimportance: must knowfreq 74%

basics

~20 s

Lifetime elision is rustc filling in the lifetimes a function signature leaves out, by fixed rules. With exactly one input lifetime, the returned reference gets it, so first_line reads as fn first_line<'a>(text: &'a str) -> &'a str.

open as a page

In Rust, what does the type `&'static str` promise, and why does every string literal have that type?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A &'static str borrows string data that stays valid until the program ends. Literal bytes are compiled into the binary and never freed, so every literal has that type; a borrow of a local String never does.

open as a page

In Rust, with `pick<'a>` tying both `&str` inputs to its result, why does E0597 appear when one input's `String` drops before the result is used?

level: middleimportance: must knowfreq 68%

basics

~20 s

rustc picks 'a as the region where both borrows are valid, so the result cannot outlive the shorter-lived String. Using it after that String drops breaks the contract, and rustc reports E0597 against that argument at the call.

open as a page

What are Rust's three lifetime elision rules, and how does the `&self` rule decide what a method's returned reference borrows from?

level: middleimportance: must knowfreq 70%

basics

~20 s

Each elided input lifetime becomes its own parameter; if there is exactly one input lifetime, every elided output gets it; in a method taking &self or &mut self, elided outputs get the receiver's lifetime. Any other elided output is error E0106.

open as a page

Why does Rust's `std::thread::spawn` require a `'static` closure, and how do you fix E0373 when it borrows a local vector?

level: middleimportance: must knowfreq 66%

basics

~20 s

thread::spawn requires F: 'static because the new thread can outlive its caller, so a borrow of the caller's locals could dangle. Fix E0373 with move to hand owned data over, or move in an Arc clone to share it.

open as a page

In Rust, what does the bound `T: 'static` require of a type, and why does `String` satisfy it while `&'a str` does not?

level: middleimportance: must knowfreq 62%

basics

~20 s

T: 'static means the type holds no borrow shorter than 'static: it owns its data or borrows only 'static data. String owns its bytes; &'a str with a shorter 'a does not qualify. The value can still be dropped anytime.

open as a page

In Rust, why does a struct that stores a `&[u8]` field need a lifetime parameter, and what must its `impl` block declare?

level: middleimportance: must knowfreq 70%

basics

~20 s

A reference field borrows data the struct does not own, so rustc needs a lifetime parameter, as in struct HeaderParser<'a> { src: &'a [u8] }, to check no instance outlives that data. The impl must declare it as well: impl<'a> HeaderParser<'a>.

open as a page

In Rust, why does pushing a closure that borrows a local `String` into a `Vec<Box<dyn Fn(&Request) -> Response>>` field fail to compile?

level: juniorimportance: should knowfreq 38%

basics

~20 s

Written in a field or signature, Box<dyn Fn(&Request) -> Response> means Box<dyn Fn(&Request) -> Response + 'static>, so the closure may not borrow shorter-lived data. A borrowed local fails with E0597; move owned data in or declare + 'a.

open as a page

In Rust, why does passing a `&'static str` and a short-lived local borrow to `fn log_pair<'a>(key: &'a str, value: &'a str)` compile?

level: juniorimportance: should knowfreq 30%

basics

~20 s

Because 'static outlives every 'a, &'static str is a subtype of &'a str, and &'a T is covariant in 'a. rustc infers 'a as the short region where the local borrow lives and shrinks the literal to it at the call.

open as a page

In Rust, why does `fn load_host<'a>() -> &'a str` returning `raw.trim()` of a local `String` fail with E0515, and why can no annotation fix it?

level: middleimportance: should knowfreq 55%

basics

~20 s

raw is dropped when load_host returns, so a borrow of it would dangle, and rustc reports E0515. An output lifetime tied to no input lets the caller choose any lifetime, which only data valid everywhere, such as a literal, can satisfy.

open as a page

In Rust, what does the anonymous lifetime `'_` mean in `impl fmt::Display for TextBuffer<'_>` and in a return type such as `SplitWhitespace<'_>`?

level: middleimportance: should knowfreq 40%

basics

~20 s

'_ is the anonymous lifetime: an elided lifetime written out. In an impl header each '_ becomes a fresh lifetime parameter; in a function signature it follows the elision rules, so SplitWhitespace<'_> returned from a &self method borrows from self.

open as a page

Which Rust function signatures make lifetime elision fail with E0106, and how should you judge the fix rustc suggests?

level: middleimportance: should knowfreq 55%

basics

~20 s

E0106 appears when an elided output lifetime matches no rule: no input lifetime, several input lifetimes with no &self receiver, or two positions inside one parameter. rustc's suggested lifetime compiles but can over-constrain; name only the input the output really borrows from.

open as a page

Why does the Rust method `fn line_or(&self, n: usize, fallback: &str) -> &str` fail to compile when it may return `fallback`?

level: middleimportance: should knowfreq 50%

basics

~20 s

Elision gives the output the lifetime of &self, while fallback gets its own unrelated lifetime, so returning fallback breaks the signature: lifetime may not live long enough. Name one lifetime on &self, fallback and the output, or return only data from self.

open as a page

In Rust, why does rustc reject a `HeaderParser<'a>` used after its byte buffer is dropped, or built from `&read_request()`?

level: middleimportance: should knowfreq 55%

basics

~20 s

A struct holding a reference is itself a borrow of its source. Using it after a named buffer is dropped is E0597; building it from a temporary freed at the end of the let statement is E0716. Bind the bytes to a longer-lived local.

open as a page

In Rust, why does adding a `Cell<Option<&'a str>>` field to `Arena<'a>` make a call mixing an `Arena<'static>` and a local arena fail with E0597?

level: middleimportance: should knowfreq 20%

basics

~20 s

A struct's variance comes from its fields, and Cell<T> is invariant in T, so the new field makes Arena invariant in 'a. rustc can no longer shrink Arena<'static> to the local lifetime, so the local data must live for 'static.

open as a page

A Rust tokenizer `fn next_token<'a>(src: &'a str, delims: &'a str) -> &'a str` causes E0597 at callers that drop the delimiter `String` early; why, and what fixes it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The shared 'a tells rustc the token may borrow from delims as well as src, so callers must keep the delimiter String alive as long as the token. Giving delims its own or an elided lifetime ties the output to src alone.

open as a page

On a Rust `TextBuffer<'a>` holding `&'a str`, why does `TextBuffer::new(&src).first_line()` fail with E0716 when `first_line(&self) -> &str` relies on elision?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Elision ties first_line's result to the borrow of self, the temporary TextBuffer, not to 'a, the source text. The temporary is freed at the end of the let statement, so the result cannot be used afterwards: E0716. Returning &'a str fixes it.

open as a page

In Rust, why does `fn health_check<'a, F: Fn(&'a Request) -> Response>(handler: F)` fail when it calls `handler` on a local `Request`, and what does `for<'a>` change?

level: seniorimportance: should knowfreq 28%

basics

~20 s

With 'a declared on the function, the caller picks one lifetime that outlives the call, and a local Request cannot live that long, so rustc reports E0597. F: for<'a> Fn(&'a Request) -> Response requires F to accept every lifetime, the local's included.

open as a page

In a long-running Rust service, when is `Box::leak` an acceptable way to get a `&'static` reference, and what does it cost?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Box::leak safely turns a Box into a &'static mut by never freeing it. It suits data built once that must last the whole process, like startup config. Drop never runs, and leaking per request grows memory without bound.

open as a page

In Rust, why does collecting lines from `fn next_line(&mut self) -> Option<&[u8]>` on a `HeaderParser<'a>` fail with E0499, and how does `&'a [u8]` fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

With the output elided, each returned slice is tied to the &mut self borrow, so a line kept alive keeps the parser mutably borrowed and the next call is E0499. Returning &'a [u8] ties the slice to the buffer instead.

open as a page

In Rust, why can't a `Document` struct own its `String` text and also hold `&str` slices into that same text?

level: seniorimportance: should knowfreq 55%

basics

~20 s

No lifetime can name the struct's own field: 'a must come from a borrow outside the value. A constructor fails with E0515 and E0505, and a value built in place is frozen. Store offsets, or split owner and view.

open as a page

In Rust, why does `overwrite(&mut label, &input)` fail with E0597 when `label: &'static str` and `overwrite` takes `&mut &'a str` and `&'a str`?

level: seniorimportance: should knowfreq 30%

basics

~20 s

&mut T is invariant in T, so &mut &'static str cannot be treated as &mut &'a str. That forces 'a to 'static, so the borrow of input must last for 'static and rustc rejects it; otherwise label would dangle once input drops.

open as a page

In Rust, a `Handle<'arena>` holding only a `u32` index fails with E0392 - which `PhantomData` field fixes it, and how does that choice set variance?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Add a zero-sized PhantomData field that mentions 'arena. PhantomData<&'arena Arena> makes the handle behave like a shared borrow: covariant in 'arena and tied to the arena. PhantomData<Cell<&'arena ()>> or PhantomData<fn(&'arena ()) -> &'arena ()> would make it invariant.

open as a page

When designing a long-lived Rust API type such as a parsed HTTP request, how do you decide whether its fields borrow (`&'a [u8]`) or own their data?

level: principalimportance: should knowfreq 35%

basics

~20 s

Borrowing avoids copies but puts a lifetime parameter on every holder and pins the value to its buffer. Own data in long-lived or shared types; keep borrowed views local, with a conversion to an owned form.

open as a page

In Rust, why does boxing `let h = |_req| Response(200);` as a `Box<dyn Fn(&Request) -> Response>` fail with "implementation of `Fn` is not general enough"?

level: middleimportance: nice to knowfreq 18%

basics

~20 s

A closure written on its own with an unannotated parameter gets that parameter's type from later use, as &Request for one specific lifetime, so it implements Fn for that lifetime only. The box needs every lifetime; annotate |r: &Request| or write the closure inline.

open as a page

In Rust, when must a function signature carry an outlives bound such as `where 'a: 'b`, rather than one lifetime shared by every reference?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

'a: 'b means 'a lasts at least as long as 'b. It is needed when two lifetime parameters must stay distinct, for example one pinned behind &mut, yet data borrowed for 'a is returned as 'b; otherwise one shared lifetime usually suffices.

open as a page

In Rust, why does a function taking `&dyn Fn(&Request) -> Response` accept a closure that borrows a local, while one taking `&Box<dyn Fn(&Request) -> Response>` rejects it?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

The default object lifetime is taken first from the type directly containing the trait object. &'a dyn Trait means &'a (dyn Trait + 'a), but in &'a Box<dyn Trait> the container is Box, which sets no bound, so the object is + 'static.

open as a page

In Rust, why can a `Hook<'s>` holding `fn(&'s str)` be passed where `Hook<'static>` is expected, but not once the field becomes `fn(&'s str) -> &'s str`?

level: seniorimportance: nice to knowfreq 10%

basics

~20 s

fn(T) is contravariant in its argument: a callback that accepts any &'s str also accepts every &'static str, so Hook<'s> is a subtype of Hook<'static>. Returning &'s str adds a covariant use, and mixed uses make Hook invariant.

open as a page