skip to content

In Rust, why does `-> impl Fn(u32) -> u32` reject an if/else returning two different capturing closures, and how do you fix it?

level: middleimportance: should knowfreq 55%

answer

  1. one hidden type per function
  2. every closure is its own type
  3. non-capturing closures coerce
  4. fold the branch into data

basics

~20 s

Return-position impl Trait stands for one concrete type, and every closure has its own unique type, so two capturing closures give E0308. Return one move closure over the varying data, or box both as Box<dyn Fn>.

solid answer

~40 s

`-> impl Fn(u32) -> u32` hides a single concrete type chosen by the body; it does not allow a different type per path. Each closure expression has its own anonymous type, so an `if`/`else` returning two capturing closures fails with E0308 and the note "no two closures, even if identical, have the same type". Non-capturing closures are the exception: both coerce to a `fn(u32) -> u32` pointer, so that version compiles. The cheapest fix is to compute what differs first and return one `move` closure. When the variants truly differ, return `Box<dyn Fn(u32) -> u32>`, paying one allocation and a vtable call.

code

plaintext · 19 lines
plaintext
error[E0308]: `if` and `else` have incompatible types
 --> q3err4.rs:5:9
  |
2 | /     if coupon > 0 {
3 | |         move |cents| cents * percent / 100 - coupon
  | |         -------------------------------------------
  | |         |
  | |         the expected closure
  | |         expected because of this
4 | |     } else {
5 | |         move |cents| cents * percent / 100
  | |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected closure, found a different closure
6 | |     }
  | |_____- `if` and `else` have incompatible types
  |
  = note: expected closure `{[email protected]:3:9: 3:21}`
             found closure `{[email protected]:5:9: 5:21}`
  = note: no two closures, even if identical, have the same type
  = help: consider boxing your closure and/or using it as a trait object

go deeper

for a junior

Recall that every closure has its own type and that -> impl Fn still means exactly one type per function.

for a middle

Explain the E0308 message, the non-capturing exception through fn pointers, and the fold-into-one-closure fix before reaching for a Box.

for a senior

Decide when a trait object is unavoidable: types picked at run time, values from different functions in one collection, or fields without generics.

for a principal

Keep returned closures unboxed on hot paths by making the varying part data, and reserve boxed callbacks for genuinely open sets of behaviour.

## One function, one hidden type Return-position `impl Trait` stands for **one concrete type** that the function body chooses. The Rust Reference states it directly: "Each possible return value from the function must resolve to the same concrete type." The keyword hides the type from the caller; it does not let the function return different types on different paths. This collides with closures. A closure is compiled into an anonymous struct whose fields are its captured variables, plus an implementation of the `Fn` traits whose body is the closure's code. Two closures with different captures have different layouts, and even two textually identical closures are distinct items. So every closure expression has its **own unique, anonymous type**, even when two closures have identical text, captures and signatures. So a function that returns one of two capturing closures returns two different types: ```rust fn pricing(percent: u32, coupon: u32) -> impl Fn(u32) -> u32 { if coupon > 0 { move |cents| cents * percent / 100 - coupon } else { move |cents| cents * percent / 100 } } ``` rustc 1.99.1 rejects this with **E0308**, "`if` and `else` have incompatible types", and the notes "expected closure, found a different closure" and "no two closures, even if identical, have the same type". An early `return` of one closure followed by a tail expression returning another fails with the same E0308 and the same note. ## The exception: closures that capture nothing If **neither** closure captures a variable, the `if`/`else` compiles. Non-capturing closures can coerce to a function pointer type such as `fn(u32) -> u32`, and rustc finds that common type for the two branches, so the hidden type of the opaque return is a plain `fn` pointer. Once either closure captures something, that coercion is unavailable; casting it with `as fn(u32) -> u32` fails with the note "closures can only be coerced to `fn` types if they do not capture any variables". ## Fixes 1. **Move the branch into the data.** Compute what differs first, then return a single `move` closure. One closure expression means one type, no allocation and static dispatch: ```rust fn pricing(percent: u32, coupon: u32) -> impl Fn(u32) -> u32 { move |cents| (cents * percent / 100).saturating_sub(coupon) } ``` 2. **Box the closures** and return `Box<dyn Fn(u32) -> u32>`. Each branch becomes `Box::new(closure)`; the two closure types erase to one trait-object type. This costs one allocation per call and a vtable call per invocation, and it is the suggestion rustc itself prints with the error. 3. **Return a function pointer** when every closure is non-capturing, or return named `fn` items, which coerce to a common `fn` pointer type in the same way. Fix 1 is usually best: the branch moves from choosing **code** to choosing **data**, the closure stays inline at its call sites, and the signature does not change, so callers are unaffected. Fix 2 is the honest choice when the behaviours differ in more than a few values. ## When `Box<dyn Trait>` is still required `impl Trait` cannot replace a trait object when: - the concrete type depends on a run-time value and the variants cannot be folded into one closure or one type; - values from **different** functions must sit in one collection: `vec![ninety(), flat()]`, with each function returning `impl Fn(u32) -> u32`, fails with E0308 and the note "distinct uses of `impl Trait` result in different opaque types"; - a value must be stored in a struct field without making the struct generic. By contrast, `vec![pricing(90), pricing(80)]` **compiles**: both calls go through the same function with the same generic arguments, so they return the same opaque type. ## Summary table | Situation | Compiles with `-> impl Fn(u32) -> u32`? | |---|---| | One closure expression, captured data varies | yes | | Two non-capturing closures in `if`/`else` | yes, via a common `fn` pointer type | | Two capturing closures in `if`/`else` | no, E0308 | | Results of one function in one `Vec` | yes | | Results of two functions in one `Vec` | no, E0308 | ## Pitfalls - Reading `impl Fn` as "anything callable, chosen per call": it is one hidden type per function. - Forgetting `move`: returning a closure that borrows a parameter fails with **E0373**, "closure may outlive the current function". - Reaching for `Box<dyn Fn>` first: it works, but folding the branch into one closure is usually free.

  • In Rust, why does the if/else version compile when neither closure captures a variable?
    A closure that captures nothing can coerce to a function pointer type. Faced with two such closures in `if`/`else`, rustc coerces both to `fn(u32) -> u32`, so the function returns one concrete type, a `fn` pointer, behind the opaque `impl Fn`. A capturing closure cannot make that coercion, which is why the capturing version fails.
  • In Rust, does `vec![pricing(90), pricing(80)]` compile when `pricing` returns `impl Fn(u32) -> u32`?
    Yes. Both calls go through the same function with the same generic arguments, so they return the same opaque type and fit in one `Vec`. Mixing results of two different functions, each returning `impl Fn(u32) -> u32`, fails with E0308 because distinct uses of `impl Trait` are distinct opaque types; that case needs `Box<dyn Fn(u32) -> u32>`.

  • impl Fn lets each branch return a different closure type
  • Two closures with identical code have the same type
  • Casting a capturing closure with as fn makes the branches agree
  • Every returned closure has to be boxed as Box<dyn Fn>
  • Two functions returning impl Fn(u32) -> u32 return the same type