In Rust, why does a config lookup `fn pick(primary: &str, fallback: &str) -> &str` need a lifetime parameter, and what does `'a` promise?
answer
- two inputs, one output borrow
- signature must name the source
- same 'a on all three
- result valid for the shorter borrow
basics
~20 sThe 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 sThe 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 linesfn pick(primary: &str, fallback: &str) -> &str {
if primary.is_empty() { fallback } else { primary }
}
fn main() { println!("{}", pick("", "x")); }go deeper
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.
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.
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.
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.