skip to content

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%

answer

  1. rules from RFC 599 and RFC 1156
  2. the containing type decides first
  3. &'a T requires T: 'a
  4. innermost object sets the bound

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.

solid answer

~50 s

When a trait object's bound is omitted, rustc applies the default object lifetime rules (RFC 599, amended by RFC 1156). An explicit bound wins, and `'_` follows ordinary elision. Otherwise the generic type that directly contains the object decides: `&'a T` requires `T: 'a`, so `&'a dyn Trait` means `&'a (dyn Trait + 'a)`, and a borrowing closure fits. Two bounds there are ambiguous (E0228). With no bound from the container, the trait's own lifetime bound is used, and failing that the bound is `'static` outside expressions. In `&'a Box<dyn Trait>` the container is `Box`, which declares none, so the object is `+ 'static` and the outer reference does not reach inside. Fix it by taking `&dyn Trait`, or writing `&Box<dyn Trait + '_>`. A returned `Box<dyn Trait>` capturing an argument needs `+ '_` for the same reason.

code

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

// &dyn Trait: the object bound defaults to the reference's own lifetime.
fn call_ref(h: &dyn Fn(&Request) -> Response, r: &Request) -> u16 {
    h(r).0
}

// The innermost object sets the bound: without + '_ this parameter
// would mean &Box<dyn Fn(&Request) -> Response + 'static>.
fn call_boxed(h: &Box<dyn Fn(&Request) -> Response + '_>, r: &Request) -> u16 {
    h(r).0
}

// A returned Box defaults to 'static; + '_ ties it to `prefix` instead.
fn guard(prefix: &str) -> Box<dyn Fn(&Request) -> Response + '_> {
    Box::new(move |r: &Request| Response(if r.path.starts_with(prefix) { 403 } else { 200 }))
}

fn main() {
    let prefix = String::from("/admin");
    let req = Request { path: "/admin/users".into() };
    let boxed: Box<dyn Fn(&Request) -> Response + '_> = Box::new(guard(&prefix));
    println!("{} {}", call_ref(&*boxed, &req), call_boxed(&boxed, &req));
}

go deeper

for a junior

Know that a trait object has a lifetime bound even when none is written, and that Box<dyn Trait> in a signature means + 'static.

for a middle

Explain why &'a dyn Trait borrows its object bound from the reference, and why adding + '_ to a returned Box lets it capture an argument.

for a senior

Walk the rule order on unfamiliar types, spot the &Box<dyn Trait> trap in review, and resolve E0228 by naming the bound.

for a principal

Set the team rule for handler parameters, &dyn by default and explicit + 'a on stored boxes, so hidden 'static requirements do not leak into public APIs.

## The default object lifetime bound Every trait object type `dyn Trait` carries a **lifetime bound**, written `dyn Trait + 'x`, that limits how long the erased value behind it is allowed to hold borrows. Writing it everywhere would be noisy, so the language defines a **default object lifetime bound** used whenever the `+ 'x` is left out entirely. The rules come from RFC 599 and its amendment RFC 1156, and the Rust Reference lists them in its lifetime-elision chapter. They are not the function-signature elision rules: a trait object's omitted bound never becomes a fresh lifetime parameter. ## The rules, in order 1. **An explicit bound wins.** `dyn Trait + 'a` means exactly that. Writing `'_` as the bound makes it follow the ordinary elision rules instead of the object defaults. 2. **The containing type decides next.** If the object is a type argument of a generic type, that type's bounds on the parameter are consulted. A unique lifetime bound becomes the default; more than one is ambiguous and rustc reports **E0228** "cannot deduce the lifetime bound for this trait object type from context". 3. **Then the trait's own bounds.** A trait declared with a single lifetime bound, such as `trait Bar<'a>: 'a`, gives that bound; if `'static` is any of its bounds, the default is `'static`. 4. **Otherwise:** the bound is inferred inside expressions and is `'static` outside them. ## Applying them | Written type | Meaning after defaults | Why | |---|---|---| | `&'a dyn Handler` | `&'a (dyn Handler + 'a)` | `&'a T` requires `T: 'a` | | `&'a mut dyn Handler` | `&'a mut (dyn Handler + 'a)` | same rule for `&'a mut T` | | `Box<dyn Handler>` | `Box<dyn Handler + 'static>` | `Box<T>` has no lifetime bound on `T` | | `Rc<dyn Handler>`, `Arc<dyn Handler>` | `... + 'static` | no lifetime bound on `T` either | | `std::cell::Ref<'b, dyn Handler>` | `Ref<'b, dyn Handler + 'b>` | declared as `Ref<'b, T: ?Sized + 'b>` | | `&'a Box<dyn Handler>` | `&'a Box<dyn Handler + 'static>` | the innermost container, `Box`, decides | ## The `&Box` trap The last row is the one that surprises people. The Reference says it directly: the innermost object sets the bound, so `&'a Box<dyn Foo>` is still `&'a Box<dyn Foo + 'static>`. The `&'a` constrains the `Box`, not the object inside it. A function written as `fn call_boxed(h: &Box<dyn Fn(&Request) -> Response>, ...)` therefore demands a `'static` handler, and passing it a box whose closure borrows a local `prefix` fails with **E0597**, "coercion requires that `prefix` is borrowed for `'static`". The same handler passed to `fn call_ref(h: &dyn Fn(&Request) -> Response, ...)` compiles, because there the reference is the container and lends the object its own lifetime. ## Return position and `'_` A function that builds a handler from a borrowed argument hits rule 4 in a signature: - `fn guard(prefix: &str) -> Box<dyn Fn(&Request) -> Response>` means `+ 'static`, so returning a `move` closure that captured `prefix`, itself a `&str`, fails with "lifetime may not live long enough". - rustc's help says to declare that the trait object captures data from argument `prefix` by adding an explicit `'_` bound. - `-> Box<dyn Fn(&Request) -> Response + '_>` then follows ordinary elision: the single input lifetime becomes the object's bound. ## Where the defaults meet signature elision The two rule sets cooperate rather than compete. The reference lifetime is decided by function elision; the object bound inside it is then decided by the object rules: - `fn get_mut(&mut self) -> &mut dyn Handler` elides to `&'s mut dyn Handler`, with `'s` the receiver's lifetime, and rule 2 makes that `&'s mut (dyn Handler + 's)`. - `Box<dyn Handler + '_>` as an argument type gets a fresh lifetime, like any elided input, so a function can accept a boxed handler that borrows the caller's data. - `Box<dyn Handler>` as an argument type stays `+ 'static`: no elision happens, because nothing was written to elide. ## Practical rules - Prefer `&dyn Trait` or `&mut dyn Trait` parameters over `&Box<dyn Trait>`. They are more general and avoid the hidden `'static`. - When a returned or stored `Box<dyn Trait>` captures borrowed data, write `+ '_` or `+ 'a` deliberately; the default is `'static`. - Rc and Arc behave like Box: no lifetime bound on their parameter, so the default is `'static`. - On E0228, name the bound explicitly; the compiler will not pick one of two candidates for you. - `impl dyn Trait { ... }` also uses rule 4, so it is an impl for `dyn Trait + 'static` only.

  • What does rustc do with `type Wrapped<'a, 'b> = TwoBounds<'a, 'b, dyn Handler>` when TwoBounds declares `T: ?Sized + 'a + 'b`?
    It refuses with E0228, "cannot deduce the lifetime bound for this trait object type from context". The containing type offers two lifetime bounds and the rules do not choose between them, so you write one explicitly, such as `dyn Handler + 'b`.
  • How does a lifetime bound on the trait itself change the default?
    When the container gives no bound, the trait's bounds are used. For `trait Bar<'a>: 'a`, the Reference states that `Box<dyn Bar<'a>>` means `Box<dyn Bar<'a> + 'a>`. If `'static` is any of the trait's lifetime bounds, the default is `'static`.

  • An omitted trait-object bound is a fresh elided lifetime, like a reference parameter.
  • The outer &'a in &'a Box<dyn Trait> also bounds the object inside the Box.
  • Rc<dyn Trait> is non-'static by default because Rc is reference-counted.
  • &'a dyn Trait always means &'a (dyn Trait + 'static).
  • rustc picks the shorter lifetime when a container has two lifetime bounds.