skip to content

In Rust, why does one `Vec<Button<F>>` reject two buttons built from different closures, and how do you call a closure stored in a field?

level: seniorimportance: should knowfreq 45%

answer

  1. anonymous type per expression
  2. a struct of its captures
  3. generic F fixes one type
  4. parentheses around the field

basics

~20 s

Every Rust closure expression has its own unique, anonymous type, so two closures, even identical ones, are two different F types, and one Vec<Button<F>> needs a single F (E0308). Box<dyn FnMut()> lets them mix; call a field as (self.on_click)().

solid answer

~40 s

The Reference says each closure expression has "a unique, anonymous type that cannot be written out", roughly a struct holding its captures. A `Button<F: FnMut()>` with `on_click: F` is a different type for every closure, so `vec![Button { on_click: || .. }, Button { on_click: || .. }]` fails with E0308 and the note "no two closures, even if identical, have the same type". The generic field costs nothing: no allocation, a direct call, and size equal to the captures. To keep different closures in one collection, store `Box<dyn FnMut()>` instead. Calling the field as `self.on_click()` is E0599, field, not a method; write `(self.on_click)()`.

code

rust · 19 lines
rust
struct Button<F: FnMut()> {
    label: String,
    on_click: F,
}

impl<F: FnMut()> Button<F> {
    fn click(&mut self) {
        (self.on_click)(); // a field holding a closure is called through parentheses
    }
}

fn main() {
    let mut clicks = 0;
    let mut ok = Button { label: String::from("OK"), on_click: || clicks += 1 };
    ok.click();
    ok.click();
    println!("{} pressed", ok.label);
    println!("clicks = {clicks}");
}

go deeper

for a junior

Recall that each closure has its own type you cannot write, and that a stored closure is called as (self.field)().

for a middle

Explain why a generic field pins one closure type, read the E0308 note, and show the boxed alternative.

for a senior

Choose generic fields or boxed handlers by allocation, dispatch and collection needs, and explain a closure's size as its captures.

for a principal

Set the callback storage convention for a UI or event library, generic for hot single handlers and boxed for registries.

## Each closure is its own type In Rust every **closure expression** produces a value of a fresh, compiler-generated type. The Reference puts it as "a unique, anonymous type that cannot be written out". Two closures with identical text and identical captures are still two types, because the type belongs to the expression, not to its behaviour. This is why a closure's type never appears in source code. You can bind it with `let`, pass it to a generic parameter `F: FnMut()`, return it as `impl Fn()`, or erase it behind `dyn`, but you cannot write `let f: <the closure type> = ...` or a field of that type. ## A closure type is a struct of its captures The Reference describes a closure type as "approximately equivalent to a struct which contains the captured values". You can see it with `std::mem::size_of_val`, which rustc 1.99.1 on a 64-bit target reported as: | closure | captures | size | |---|---|---| | `\|\| println!("hi")` | nothing | 0 | | `\|\| println!("{theme}")` | `&String` | 8 | | `move \|\| println!("{theme} {volume}")` | `String` and `u64` | 32 | The exact numbers are layout details, not a guarantee, but the model holds: a closure stores its captures and nothing else, and calling it is a direct call to code generated for that type. ## Storing a closure in a field A UI button that runs a handler on click can hold the closure in two ways: ```rust struct Button<F: FnMut()> { label: String, on_click: F } // generic struct BoxedButton { label: String, on_click: Box<dyn FnMut()> } // erased ``` The trade-offs: - **Generic `F`.** No heap allocation, a statically dispatched call, and `Button` is exactly as big as its label plus the captures. But every `Button<F>` with a different closure is a different type, so they cannot share one `Vec`, one array, or one `match` arm's result type. - **`Box<dyn FnMut()>`.** One heap allocation per handler and a call through a vtable, but every button has the same type and a `Vec<BoxedButton>` holds any mix. A boxed closure without a lifetime is `'static`, so it cannot borrow locals; that is why such handlers are usually `move` closures. The failing collection looks like this: ```plaintext error[E0308]: mismatched types = note: no two closures, even if identical, have the same type = help: consider boxing your closure and/or using it as a trait object ``` The same error appears whether or not the closures capture anything, because the generic field pins the exact closure type. A bare `vec![|| println!("a"), || println!("b")]` with non-capturing closures does compile, because they coerce to a common function pointer type; that coercion and the choice between `impl Fn` and `Box<dyn Fn>` are covered with `Fn`, `FnMut` and `FnOnce`. ## Calling a closure field Method-call syntax looks for a **method**, not a field. With `on_click: F`, `self.on_click()` fails: ```plaintext error[E0599]: no method named `on_click` found for mutable reference `&mut Button<F>` in the current scope | ^^^^^^^^ field, not a method help: to call the type parameter stored in `on_click`, surround the field access with parentheses ``` The fix is `(self.on_click)()`: the parentheses make the field access an expression, which is then called. An `FnMut` field needs `&mut self` for the call, because calling it may mutate its captures. ## A field that borrows A `Button` whose closure captures `&mut clicks` carries that borrow inside it. `clicks` stays exclusively borrowed until the button's last use; once the button is no longer used, reading `clicks` compiles again. That is the ordinary borrow rule, applied to a struct that happens to hold a closure. ## Common mistakes - Expecting two identical closures to have the same type. - Writing `self.on_click()` for a closure stored in a field. - Boxing every handler by reflex when one generic field would do. - Expecting a generic `Button<F>` to fit in one `Vec` with different closures. ## Choosing in practice A small decision list for a closure field: 1. **One handler per value, chosen at construction, called on a hot path:** a generic `F` keeps the call direct and the struct allocation-free. 2. **Handlers of different closures kept together, or chosen at run time:** a boxed `dyn` field gives every value one type at the cost of an allocation and an indirect call. 3. **A handler that borrows local data:** a generic `F` carries the borrow inside its type with no annotation, while a boxed field must spell it out as `Box<dyn FnMut() + 'a>` with a lifetime parameter on the struct; otherwise the closure must own its captures. Whichever field type you pick, the unique closure type is why the question arises at all: the compiler knows the exact type of every closure, and your struct either carries that type as a parameter or erases it.

  • In Rust, why can't you write a closure's type in a struct field or a `let` annotation?
    The type is generated by the compiler for that one closure expression and has no name in the language. You refer to it indirectly: a generic parameter `F: FnMut()` on the struct, `impl Fn()` in a return type, or a trait object such as `Box<dyn FnMut()>` that erases it.
  • In Rust, when is a generic `Button<F>` the better choice over `Box<dyn FnMut()>`?
    When each button's handler is known where the button is built and buttons do not need to share one collection type. The generic version avoids an allocation and a vtable call, and its size is just its fields plus the captures. Once handlers of different closures must sit in one `Vec`, the boxed field is the simpler fit.

  • Two closures with identical bodies and captures have the same type.
  • self.on_click() calls a closure stored in the on_click field.
  • A closure always carries a heap allocation, like a boxed function object.
  • A Vec<Button<F>> can hold any buttons whose closures share a signature.
  • You can name a closure's type in a let annotation once you know its signature.