skip to content

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%

answer

  1. when the signature is decided
  2. one lifetime, not every lifetime
  3. annotate the parameter
  4. or write the closure inline

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.

solid answer

~50 s

rustc fixes a closure's signature where the closure is written. When the closure is passed straight to something with an expected signature, such as an `F: Fn(&Request) -> Response` bound or a `Box<dyn Fn(&Request) -> Response>` target, it deduces the signature from that expectation, higher-ranked lifetimes included. A parameter annotated as `&Request` with an elided lifetime also becomes higher-ranked. But `let h = |_req| ...` has neither: the parameter type is an inference variable, later resolved to `&'x Request` for one region `'x`, so the closure implements `Fn<(&'x Request,)>` only, and rustc says it is not general enough because the box needs `for<'a>`. A related case: `|r: &Request| &r.path[..]` fails with "lifetime may not live long enough", because the return's elided lifetime is not tied to the parameter's, even with `-> &str` written. On stable, route it through a helper with a `for<'a> Fn(&'a Request) -> &'a str` bound.

code

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

fn borrowing<F>(f: F) -> F
where
    F: for<'a> Fn(&'a Request) -> &'a str,
{
    f
}

fn main() {
    // Annotated parameter: the elided lifetime becomes higher-ranked.
    let len = |r: &Request| Response(r.path.len() as u16);
    let boxed: Box<dyn Fn(&Request) -> Response> = Box::new(len);

    // A returned borrow: route the closure through a for<'a> bound.
    let path_of = borrowing(|r| &r.path[..]);

    let req = Request { path: String::from("/admin") };
    println!("{} {}", boxed(&req).0, path_of(&req));
}

go deeper

for a junior

Remember the quick fix: annotate a stored closure's reference parameter, as |r: &Request|, or write the closure where it is used.

for a middle

Explain that rustc fixes a closure's signature where it is written, from an expected bound, annotations or later use, and why only the first two give a higher-ranked signature.

for a senior

Diagnose not-general-enough and lifetime-may-not-live-long-enough errors on closures quickly, and reach for a for<'a> helper bound or a fn item when a closure must return a borrow.

for a principal

No lead decision lives here; at most, shape callback APIs so closures written inline at the call site infer correctly, instead of asking callers for helper functions.

## The error Storing a handler that was first bound to a variable looks harmless: ```rust let h = |_req| Response(200); let b: Box<dyn Fn(&Request) -> Response> = Box::new(h); ``` rustc 1.99 rejects it: "implementation of `Fn` is not general enough", with the note that the closure "must implement `Fn<(&'1 Request,)>`, for any lifetime `'1`" but "actually implements `Fn<(&'2 Request,)>`, for some specific lifetime `'2`". It also suggests adding an explicit type annotation to the closure's argument. Writing `|r: &Request| Response(200)` compiles. ## How rustc decides a closure's signature A closure's parameter and return types are settled from what is known **where the closure expression appears**: 1. **An expected signature.** If the closure is written directly as an argument whose parameter has an `F: Fn(&Request) -> Response` bound, or directly where a `dyn Fn(&Request) -> Response` is expected, rustc deduces the signature from that expectation, higher-ranked lifetimes included. 2. **Annotations.** A parameter written as `r: &Request` has an elided lifetime, and that elided lifetime becomes a fresh lifetime for each call: the closure is higher-ranked over it. 3. **Neither.** An unannotated parameter gets an inference variable. Later uses resolve it, and a reference type resolved this way carries **one** region the borrow checker solves for. `let h = |_req| ...` falls into case 3. The `let` gives no expected type, and only the later `Box::new(h)` reveals that `_req` is some `&Request`, by which point the closure has one concrete signature. ## Why one lifetime is not enough `Box<dyn Fn(&Request) -> Response>` contains `dyn for<'a> Fn(&'a Request) -> Response`: callers may pass a request borrowed for any region, a fresh one each call. A closure implementing `Fn<(&'x Request,)>` for a single `'x` cannot promise that, so the coercion fails. The same happens when such a closure is passed to `fn register<F: Fn(&Request) -> Response>(f: F)`: that bound is higher-ranked too. Later uses can pin down what type a parameter has, but they do not turn a signature that was inferred with one lifetime into one that is generic over all lifetimes. That is why the compiler's suggestion is about the closure's own text, not about the box: - rustc points at the coercion or the call, where the mismatch is detected. - Its help line adds a type annotation on the closure's argument, where the fix belongs. - Two errors appear, one for `Fn` and one for `FnOnce`, because `Fn` requires `FnMut`, which requires `FnOnce`; one annotation clears both. ## Fixes - **Annotate the parameter:** `|r: &Request| ...` is case 2, higher-ranked from the start, and can be stored, boxed or passed anywhere. - **Write the closure inline** where the expectation lives: `Box::new(|r| ...)` assigned to a boxed `dyn Fn` type, or `register(|r| ...)`. This is case 1, and here the parameter's type is known, so `r.path` resolves. - **Use a `fn` item** when the handler needs no captures: function items are higher-ranked over their elided lifetimes. Leaving the parameter unannotated and using it, as in `let h = |r| Response(r.path.len() as u16)`, fails even earlier with **E0282**, type annotations needed, since the field access needs a known type. ## Returning a borrow from a closure A second, related failure involves the return type. `let path_of = |r: &Request| &r.path[..];` fails with "lifetime may not live long enough": rustc calls the parameter's lifetime `'1` and the return's `'2`, and requires that `'1` outlive `'2`. Function elision would tie them; closure expressions do not get that rule, and adding `-> &str` still gives the return an unrelated lifetime. Stable options: - Pass the closure, written inline, to a helper whose bound names the relationship: `fn borrowing<F>(f: F) -> F where F: for<'a> Fn(&'a Request) -> &'a str { f }`, then `let path_of = borrowing(|r| &r.path[..]);`. - Use a `fn` item, where elision ties the output to the single input. Explicit closure binders, `for<'a> |r: &'a Request| -> &'a str { ... }`, are the unstable `closure_lifetime_binder` feature; stable rustc rejects them with E0658. | Closure as written | Signature over `&Request` | Boxable as `dyn Fn(&Request) -> Response`? | |---|---|---| | `let h = \|_req\| ...` | one inferred lifetime | no: not general enough | | `let h = \|r: &Request\| ...` | higher-ranked | yes | | `Box::new(\|r\| ...)` into a boxed `dyn Fn` | deduced from the target | yes |

  • Why does `Box::new(|r| Response(r.path.len() as u16))` compile when assigned to a `Box<dyn Fn(&Request) -> Response>` variable?
    Written inline there, the closure has an expected signature: rustc deduces `for<'a> Fn(&'a Request) -> Response` from the target type, so `r` is known to be a `&Request` for any lifetime and the field access resolves. Bound to a `let` first, the same closure would have no expectation and fail.
  • Can you write `for<'a>` on a closure in stable Rust?
    No. `for<'a> |r: &'a Request| -> &'a str { ... }` is the unstable `closure_lifetime_binder` feature, and stable rustc 1.99 rejects it with E0658. On stable, express the relationship through a helper function whose bound is `for<'a> Fn(&'a Request) -> &'a str`, or use a `fn` item.

  • An unannotated closure parameter is just as general as an annotated one.
  • Closures can never return a reference into one of their arguments.
  • Writing -> &str on the closure ties the return to the parameter, as in a fn.
  • Adding move fixes the not-general-enough error on a boxed closure.
  • for<'a> on a closure expression is stable syntax for fixing this.