skip to content

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%

answer

  1. 'a lasts at least as long
  2. parameters that cannot merge
  3. &mut pins a lifetime
  4. data flows long to short

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.

solid answer

~40 s

`'a: 'b` reads "'a outlives 'b": a `&'a T` is valid wherever a `&'b T` is. With only shared references, one lifetime is enough, because `&'long str` can stand in for `&'short str` and rustc shrinks `'a` to the overlap. The bound matters when parameters cannot be merged: in `fn pick<'a, 'b>(seen: &mut Vec<&'a str>, primary: &'a str, fallback: &'b str) -> &'b str`, the `&mut` pins `'a` to the vector's element lifetime, so merging would force `fallback` to live as long (E0597 at the call). Keeping both without the bound makes returning `primary` fail with "lifetime may not live long enough", and rustc suggests exactly `'a: 'b`. `T: 'a` is the type form, often implied by a `&'a T` parameter.

code

rust · 18 lines
rust
fn pick<'a, 'b>(seen: &mut Vec<&'a str>, primary: &'a str, fallback: &'b str) -> &'b str
where
    'a: 'b,
{
    seen.push(primary);
    if primary.is_empty() { fallback } else { primary }
}

fn main() {
    let config = String::from("db.internal");
    let mut seen: Vec<&str> = Vec::new();
    {
        let fallback = String::from("localhost");
        let host = pick(&mut seen, &config, &fallback);
        println!("{host}");
    }
    println!("{seen:?}");
}

go deeper

for a junior

Recall that 'a: 'b reads as 'a outlives 'b, and that most functions taking shared references need only one lifetime parameter, not a bound.

for a middle

Explain that a shared reference with a longer lifetime can stand in for a shorter one, which is why merging lifetimes usually works and bounds are rarely needed.

for a senior

Recognise when a lifetime is pinned, as behind &mut, so parameters must stay apart, and add the bound in the direction data flows instead of merging and over-constraining callers.

for a principal

Prefer signatures with the fewest lifetime parameters that tell the truth; review each extra parameter and bound for whether a caller actually gains flexibility from it.

## What `'a: 'b` means An **outlives bound** relates two lifetime parameters. The Rust Reference reads `'a: 'b` as "'a outlives 'b": `'a` lasts at least as long as `'b`, so a reference `&'a T` is valid wherever a `&'b T` would be. It can be written in the generic list (`<'a, 'b: 'a>`) or in a `where` clause, on functions and on `impl` blocks alike. It is a constraint the caller must satisfy and the body may rely on. A related form, `T: 'a`, says every lifetime inside the type `T` outlives `'a`. Many such bounds are **implied**: a parameter of type `&'a T` is only well formed if `T: 'a`, so rustc assumes it inside the function without your writing it. ## When one lifetime is enough Most signatures never need an outlives bound. When every reference involved is a plain shared reference, a single parameter suffices: ```rust fn pick<'a>(primary: &'a str, fallback: &'a str) -> &'a str ``` A `&'long str` can stand in for a `&'short str`, so at each call rustc shrinks `'a` to the overlap of the two borrows. Writing `fn pick<'a, 'b>(..) -> &'b str where 'a: 'b` here says the same thing in more words. Implied bounds remove another class of cases. In `fn outer<'a, 'b>(r: &'b &'a str) -> &'b str { *r }`, the parameter type `&'b &'a str` is only well formed if `'a: 'b`, so rustc assumes it without your writing it, and the body may return the inner `&str` as a `&'b str`. ## When the parameters must stay apart The bound earns its place when two lifetimes cannot be merged, yet data flows from one into the other. Suppose the lookup also records the configured value in a log of hosts it has seen: ```rust fn pick<'a, 'b>(seen: &mut Vec<&'a str>, primary: &'a str, fallback: &'b str) -> &'b str where 'a: 'b, { seen.push(primary); if primary.is_empty() { fallback } else { primary } } ``` Two facts force the split: - `seen` is behind `&mut`, which pins `'a` to exactly the element lifetime of the caller's vector; it cannot shrink at the call. The reasons are covered with variance. - The fallback is a short-lived value, built in an inner block, that the caller does not want to keep as long as the log. If you merge everything into one `'a`, `fallback` must now live as long as the vector's elements, and the caller gets: ```plaintext error[E0597]: `fallback` does not live long enough ``` If you keep two parameters but drop the bound, the body fails instead, because it returns `primary` (valid for `'a`) where a `&'b str` is promised: ```plaintext error: lifetime may not live long enough = help: consider adding the following bound: `'a: 'b` ``` With `'a: 'b`, the body may return `primary` as a `&'b str`, the caller may drop `fallback` right after using the result, and the log keeps its long-lived entries. ## Reading and writing outlives bounds | Situation | What to write | |---|---| | only shared references, result from several inputs | one lifetime on those inputs and the output | | one lifetime pinned by `&mut` or another invariant position, data flowing to a shorter result | two parameters and `'a: 'b` | | a reference to a generic type, `&'a T` | nothing; `T: 'a` is implied | | a generic `T` and a lifetime `'a` with no `&'a T` parameter linking them, when the body needs `T: 'a` | an explicit `T: 'a` | Practical rules: 1. Start with the fewest lifetime parameters that state the truth. 2. Add a second parameter only when merging would over-constrain a caller, as with `fallback` above. 3. When rustc suggests an outlives bound, check the direction: `'a: 'b` lets `'a` data flow into `'b` positions, never the reverse. 4. Check that the bound states a relation the caller can meet; a bound that ties a short-lived input to a long-lived output simply moves the error back to the call site. ## Common misreadings - `'a: 'b` does **not** mean `'a` is shorter; the colon reads "outlives", as in `T: Trait` reading "implements". - The bound does **not** extend anything; it restricts which lifetimes callers may substitute. - It is **not** a run-time check; like every lifetime, it is checked at compile time and erased before code generation.

  • What does rustc report if the two parameters are kept but the 'a: 'b bound is removed?
    The body fails when it returns `primary`: "lifetime may not live long enough", saying the function was supposed to return data with lifetime `'b` but returns data with lifetime `'a`, with a help line suggesting the bound `'a: 'b`. The diagnostic has no E-code.
  • When must T: 'a be written explicitly?
    When nothing in the signature implies it. A parameter of type `&'a T` implies `T: 'a`, because the reference type is only well formed if it holds. A generic function that only names `'a` and `T` separately, with no such parameter, must state `T: 'a` itself if its body relies on it.

  • 'a: 'b means 'a is the shorter of the two lifetimes.
  • Every function with two reference inputs needs an outlives bound.
  • An outlives bound makes the longer value live long enough.
  • Outlives bounds are checked at run time when the function returns.