skip to content

Higher-Ranked Bounds

for<'a> says a closure or trait works for every lifetime, not one chosen by the caller. Interviewers ask where HRTBs appear and what lifetime a dyn Trait object gets by default.

on this pageshow

questions

4

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%

answer

  1. the box has an unwritten bound
  2. default object lifetime
  3. 'static outside function bodies
  4. own the data, or add + 'a

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.

solid answer

~50 s

Every trait object carries a lifetime bound, and when you omit it rustc fills in the *default object lifetime*. `Box<T>` puts no lifetime bound on `T`, so in a struct field or function signature `Box<dyn Fn(&Request) -> Response>` means `... + 'static`: everything the closure captures must be valid for `'static`. A closure that captures `prefix` by reference is only valid while `prefix` is, so rustc reports E0597 "`prefix` does not live long enough" at the coercion, with a note spelling out the object-lifetime default. There are two fixes: a `move` closure that owns its `String` satisfies `'static`, or the chain admits borrowing handlers by declaring `struct Chain<'a>` with `Box<dyn Fn(&Request) -> Response + 'a>`, so the chain cannot outlive what its handlers borrow. The `&Request` parameter is not the problem: it already accepts a request of any lifetime.

code

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

struct Chain<'a> {
    handlers: Vec<Box<dyn Fn(&Request) -> Response + 'a>>,
}

impl<'a> Chain<'a> {
    fn push(&mut self, h: impl Fn(&Request) -> Response + 'a) {
        self.handlers.push(Box::new(h));
    }
    fn run(&self, r: &Request) -> u16 {
        self.handlers.iter().map(|h| h(r).0).max().unwrap_or(200)
    }
}

fn main() {
    let prefix = String::from("/admin");
    let mut chain = Chain { handlers: Vec::new() };
    chain.push(|r: &Request| {
        if r.path.starts_with(&prefix) { Response(403) } else { Response(200) }
    });
    let req = Request { path: "/admin/users".into() };
    println!("status {}", chain.run(&req));
}

go deeper

for a junior

Recall that a Box<dyn Fn> field quietly means + 'static, so a stored closure must own what it uses. The quick fix is a move closure over owned data.

for a middle

Explain the default object lifetime: Box sets no bound, so a field or signature defaults to 'static while a let inside a function body infers it. Show both fixes, move and + 'a.

for a senior

Read rustc's object-lifetime-default note on sight and choose between owned captures and a lifetime parameter by where the chain lives, such as long-lived server state versus a per-request pipeline.

for a principal

Weigh what a lifetime parameter on a widely used handler type costs every user of it against requiring handlers to own or share their data, and set that as the API's rule.

## The code and the error A middleware chain often stores its handlers as boxed closures: `struct Chain { handlers: Vec<Box<dyn Fn(&Request) -> Response>> }`. A handler that checks a path prefix read from configuration looks natural: ```rust let prefix = String::from("/admin"); chain.push(Box::new(|r: &Request| { if r.path.starts_with(&prefix) { Response(403) } else { Response(200) } })); ``` rustc 1.99 rejects it with **E0597** "`prefix` does not live long enough", points at the coercion with "coercion requires that `prefix` is borrowed for `'static`", and adds a note: `Box<dyn for<'a> Fn(&'a Request) -> Response>` "actually means" `Box<(dyn for<'a> Fn(&'a Request) -> Response + 'static)>`. Nothing in the source says `'static`; the compiler supplied it. ## Every trait object has a lifetime bound A **trait object** such as `dyn Fn(&Request) -> Response` erases the concrete closure type, including any borrows that type holds. To keep those borrows checked, every trait object carries a **lifetime bound**: `dyn Trait + 'x` promises that whatever sits behind it is valid for at least `'x`. When you leave the bound out, rustc applies the **default object lifetime bound**: - The type that contains the object decides first. `Box<T>` declares no lifetime bound on `T`, so a `Box` gives the object nothing to inherit. - With no bound from the container or from the trait itself, the bound is `'static` **outside expressions**: in struct fields, function signatures and type aliases. - **Inside expressions** the bound is inferred instead. That is why `let h: Box<dyn Fn(&Request) -> Response> = Box::new(|r: &Request| ...)` borrowing a local compiles inside `main`, while the same type in a field does not. So the field type is really `Vec<Box<dyn Fn(&Request) -> Response + 'static>>`. ## Why the closure does not qualify A closure's type includes its captures. This closure uses `prefix` only through `starts_with(&prefix)`, so it captures `prefix` by shared reference and its type holds a `&String` borrowing a local. A type holding a borrow of a local is valid only while that local is, which is shorter than `'static`, so the unsizing coercion from the closure to the `'static` trait object fails. ## Fix 1: let the closure own its data Writing `move |r: &Request| ...` moves the `String` into the closure. The closure now holds no borrows, satisfies `'static`, and the original field type works unchanged. Two caveats: 1. `move` moves whatever the closure names. If the captured variable is itself a `&str`, the closure owns a copy of that **reference** and is still tied to the borrowed data. 2. The local is gone after the move; clone it first if the function still needs it. ## Fix 2: put a lifetime on the trait object When handlers genuinely should borrow, say so in the type: ```rust struct Chain<'a> { handlers: Vec<Box<dyn Fn(&Request) -> Response + 'a>>, } ``` Now a `Chain<'a>` accepts any handler valid for `'a`, and the borrow checker stops the chain from being used after `prefix` is dropped. The cost is that the lifetime parameter appears wherever `Chain` is named. | Field type | What handlers may capture | What the chain may do | |---|---|---| | `Box<dyn Fn(&Request) -> Response>` | owned data or `'static` borrows only | live anywhere, be stored in long-lived state | | `Box<dyn Fn(&Request) -> Response + 'a>` | borrows valid for `'a` | exist only while those borrows do | ## What is not the problem The `&Request` parameter needs no annotation. `Fn(&Request) -> Response` is shorthand for `for<'a> Fn(&'a Request) -> Response`, a bound saying the handler accepts a request borrowed for any lifetime. That parameter lifetime and the object's `+ 'static` are separate things: one is about the argument of each call, the other about what the closure itself holds. ## A checklist for this error - Read the note first. When it says the box "actually means" `... + 'static`, the bound came from a default in a field, a signature or a type alias, not from your closure. - Ask whether the handler needs to borrow at all. Configuration such as a prefix can usually be moved in, cloned in, or shared through an `Arc<str>` handle the closure owns. - If handlers must borrow, add the lifetime to the trait object and let it become a parameter of the struct that stores it. - Leave the `&Request` parameter alone: annotating it does not change what the closure captures.

  • Why does `let h: Box<dyn Fn(&Request) -> Response> = Box::new(...)` with a borrowing closure compile inside `main`?
    The `'static` default applies only outside expressions: in fields, signatures and type aliases. Inside a function body, a trait object with no explicit bound and no bound from its container or trait gets its lifetime inferred, so rustc picks a region that the captured borrow satisfies. Move the same type into a struct field and the default becomes `'static`.
  • Does adding `move` always make the closure fit a plain `Box<dyn Fn(&Request) -> Response>`?
    Only when what it captures is owned or itself `'static`. A `move` closure that captures a `prefix: &str` parameter owns a copy of the reference, so its type still borrows the caller's string. Returning such a box from a function needs `Box<dyn Fn(&Request) -> Response + '_>`, which rustc suggests in its help text.

  • The &Request parameter needs a named lifetime before the box will accept the closure.
  • Box<dyn Fn> has no lifetime at all, so it can hold any closure.
  • Adding move always makes a closure 'static, whatever it captures.
  • Switching from Box to Rc removes the 'static requirement on the handler.
  • A 'static bound means the boxed handler can never be dropped before the program exits.
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 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, 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