skip to content

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%

answer

  1. who picks the lifetime
  2. the caller's 'a outlives the body
  3. for all choices of 'a
  4. implicit in the Fn sugar

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.

solid answer

~50 s

A lifetime parameter on the function is chosen by the caller, so `'a` names some region that outlives the whole call. Borrowing a local `Request` and passing it to `handler` would require that local to live for `'a`, and rustc reports E0597 "`probe` does not live long enough" with "argument requires that `probe` is borrowed for `'a`". A higher-ranked trait bound, `F: for<'a> Fn(&'a Request) -> Response`, instead says the handler works for every possible `'a`, so the body may pass a borrow of any `Request`, however short-lived. You rarely write it, because `Fn(&Request) -> Response` elides to exactly that; `fn(&Request)` pointer types and `dyn Fn(&Request)` are higher-ranked the same way. You write `for<'a>` mainly outside the Fn sugar, as in `for<'a> &'a C: IntoIterator<Item = &'a String>` or `T: for<'a> Parse<'a>` for a trait with a lifetime parameter, or when Fn elision is ambiguous (E0106).

code

rust · 26 lines
rust
struct Request { path: String }
struct Response(u16);

// Higher-ranked: F must accept a &Request of ANY lifetime,
// including a borrow of `probe`, which exists only inside this call.
fn health_check<F>(handler: F) -> u16
where
    F: for<'a> Fn(&'a Request) -> Response, // same as F: Fn(&Request) -> Response
{
    let probe = Request { path: String::from("/health") };
    handler(&probe).0
}

// Outside the Fn sugar, for<'a> must be written out.
fn count_twice<C>(routes: C) -> usize
where
    for<'a> &'a C: IntoIterator<Item = &'a String>,
{
    (&routes).into_iter().count() + (&routes).into_iter().filter(|p| p.starts_with("/api")).count()
}

fn main() {
    let status = health_check(|r: &Request| Response(if r.path == "/health" { 200 } else { 404 }));
    let routes = vec![String::from("/api/users"), String::from("/health")];
    println!("{status} {}", count_twice(routes));
}

go deeper

for a junior

Recall that Fn(&Request) -> Response already accepts a borrow of any lifetime; for<'a> is the explicit spelling of that.

for a middle

Explain who chooses a lifetime declared on a function versus one bound by for<'a>, and why a borrow of a local cannot satisfy a caller-chosen 'a.

for a senior

Read E0597 pointing at a callback bound as a sign of a caller-chosen lifetime, rewrite it as for<'a>, and know where it must be explicit, such as &'a C: IntoIterator.

for a principal

No lead decision lives here; at most, prefer elided Fn(&T) bounds in public signatures so readers never reason about a named lifetime that buys nothing.

## Two places a lifetime can be chosen A lifetime in a generic bound has to be introduced somewhere, and where it is introduced decides **who chooses it**. - `fn health_check<'a, F: Fn(&'a Request) -> Response>(handler: F)` introduces `'a` on the **function**. Like a type parameter, it is chosen at each call site, and a lifetime parameter of a function always outlives the call itself. The bound then says: `F` accepts a `&Request` borrowed for that one caller-chosen region. - `fn health_check<F>(handler: F) where F: for<'a> Fn(&'a Request) -> Response` introduces `'a` **inside the bound**. The Rustonomicon reads `for<'a>` as "for all choices of `'a`": an unbounded list of bounds, one per lifetime, that `F` must satisfy at once. This is a **higher-ranked trait bound** (HRTB). ## Why the caller-chosen version fails Inside the body the function builds `let probe = Request { ... }` and calls `handler(&probe)`. The borrow of `probe` ends when the function returns, but the bound only promises that `handler` accepts `&'a Request`, and `'a` outlives the call. rustc 1.99 reports **E0597**, "`probe` does not live long enough", explaining that the argument requires the local to be borrowed for `'a`. No caller could choose a lifetime that fits, because the local does not exist until the body runs. | Bound | Who picks `'a` | Can the body pass a borrow of a local? | |---|---|---| | `fn f<'a, F: Fn(&'a T)>` | the caller, once per call | no: E0597 | | `F: for<'a> Fn(&'a T)` | nobody: it must hold for all | yes | | `F: Fn(&T)` (elided) | same as `for<'a>` | yes | ## Where higher-ranked bounds appear without being written The Reference's elision chapter applies the function elision rules to the parenthesised Fn sugar, and the result is higher-ranked: - `F: Fn(&Request) -> Response` means `F: for<'a> Fn(&'a Request) -> Response`. - `Fn(&str) -> &str` means `for<'a> Fn(&'a str) -> &'a str`: one input lifetime goes to the elided output. - Function pointer types are higher-ranked too: `fn(&str) -> &str` is `for<'a> fn(&'a str) -> &'a str`. - `Box<dyn Fn(&Request) -> Response>` holds a `dyn for<'a> Fn(&'a Request) -> Response`, which rustc prints in its diagnostics. So most Rust code relies on HRTBs every day without the keyword. ## When you must write `for<'a>` 1. **Bounds on a borrowed form of a type parameter.** To iterate a generic collection by reference inside the body, write `where for<'a> &'a C: IntoIterator<Item = &'a String>`. Writing `&C` with no lifetime in a where clause is E0637, and a function-level `'a` brings back E0597, plus E0309 until you add `C: 'a`. 2. **Traits with a lifetime parameter.** Given `trait Parse<'a>: Sized { fn parse(src: &'a str) -> Option<Self>; }`, a function that parses text it reads into a local needs `T: for<'a> Parse<'a>`: implemented for every lifetime, the local's included. 3. **When Fn elision cannot decide.** `F: Fn(&Request, &str) -> &str` fails with **E0106**: the output could borrow from either input. rustc suggests `F: for<'a> Fn(&'a Request, &'a str) -> &'a str`. The binder can sit before the bounded type (`for<'a> F: Fn(&'a T)`) or before the trait (`F: for<'a> Fn(&'a T)`); the Reference says the only difference is the binder's scope. ## An edge worth knowing A higher-ranked lifetime must appear in the trait's inputs. `F: for<'a> Fn(i32) -> Option<&'a i32>` is **E0582**: `'a` occurs only in the output, so no closure could honestly produce a reference valid for every lifetime from an `i32`. Use the lifetime in an input, or use `'static`. ## Spotting the mistake in review - A function-level lifetime that appears only inside a closure bound, as in `fn f<'a, F: Fn(&'a T)>(f: F)`, is a smell: nothing ties it to an argument, so it can only constrain the callback. - If the body creates a value and lends it to the callback (a probe request, a buffer, the contents of a lock guard), the bound must be higher-ranked. - If the callback receives data borrowed from an argument, as in `fn find<'a, F: Fn(&'a Item) -> bool>(items: &'a [Item], f: F) -> Option<&'a Item>`, a caller-chosen lifetime compiles, though the elided `Fn(&Item) -> bool` works just as well there. - Deleting the function-level `'a` and writing `Fn(&T)` is usually the whole fix.

  • Why is `fn total<'a, C: 'a>(c: C) where &'a C: IntoIterator<Item = &'a u32>` still wrong when the body iterates `&c`?
    `'a` is chosen by the caller and outlives the call, but `c` is a local owned by the body, so `&c` cannot be borrowed for `'a` and rustc reports E0597. Only `for<'a> &'a C: IntoIterator<Item = &'a u32>` lets the body borrow `c` for whatever short region it needs.
  • Why does `F: for<'a> Fn(i32) -> Option<&'a i32>` fail?
    It is E0582: `'a` appears only in the output, not in any input type. The bound would require a closure to return a reference valid for every lifetime out of a plain `i32`, which nothing can do. Tie the lifetime to an input, as in `for<'a> Fn(&'a i32) -> Option<&'a i32>`, or return `&'static i32`.

  • A lifetime parameter on the function lets the body choose a shorter borrow.
  • F: Fn(&Request) needs for<'a> written out before it can take a local's borrow.
  • for<'a> makes the argument 'static, the longest lifetime there is.
  • Higher-ranked bounds only exist with the for keyword, never in everyday code.
  • A for<'a> Fn bound may use its lifetime only in the return type.