skip to content

In a Rust middleware chain holding `Vec<Box<dyn FnMut(&Event)>>`, why does `for h in &self.handlers { h(e) }` fail with E0596, and how do you fix it?

level: seniorimportance: should knowfreq 35%

answer

  1. the receiver of the call
  2. a shared iterator yields shared references
  3. iter_mut and &mut self
  4. Fn plus interior mutability

basics

~20 s

Calling an FnMut needs &mut access, but iterating &self.handlers yields shared references, so rustc cannot borrow the handler mutably. Make dispatch take &mut self and use iter_mut, or store Box<dyn Fn> handlers that keep state in Cell, RefCell or a Mutex.

solid answer

~40 s

`FnMut::call_mut` takes `&mut self`, and `Box<dyn FnMut>` forwards to it, so calling a stored handler needs a mutable borrow of that box. `for h in &self.handlers` gives `&Box<dyn FnMut(&Event)>`, and rustc reports E0596, "cannot borrow `*h` as mutable, as it is behind a `&` reference", suggesting a mutable iterator. There are two fixes. Keep `FnMut` and make dispatch take `&mut self` with `iter_mut()`, so handlers can mutate their captures freely. Or store `Box<dyn Fn(&Event)>` and dispatch from `&self`, moving handler state into `Cell` or `RefCell`, or into a `Mutex` or atomics with `Send + Sync` added to the trait object when the chain is shared across threads. The first is simpler for a single owner; the second is needed when dispatch runs behind a shared reference.

code

rust · 31 lines
rust
struct Event {
    path: String,
}

struct Chain {
    handlers: Vec<Box<dyn FnMut(&Event)>>,
}

impl Chain {
    fn on(&mut self, h: impl FnMut(&Event) + 'static) {
        self.handlers.push(Box::new(h));
    }

    fn dispatch(&mut self, e: &Event) {
        for h in self.handlers.iter_mut() {
            h(e); // calling a Box<dyn FnMut> needs &mut access to it
        }
    }
}

fn main() {
    let mut chain = Chain { handlers: Vec::new() };
    let mut log: Vec<String> = Vec::new();
    chain.on(move |e| {
        log.push(e.path.clone());
        println!("seen so far: {log:?}");
    });
    chain.on(|e| println!("audit {}", e.path)); // an Fn closure fits too
    chain.dispatch(&Event { path: "/health".into() });
    chain.dispatch(&Event { path: "/login".into() });
}

go deeper

for a junior

Recall that an FnMut call needs mutable access, so a stored FnMut handler is called through iter_mut or a mut binding.

for a middle

Explain why iterating &self.handlers yields shared references, read the E0596 help, and switch dispatch to &mut self.

for a senior

Choose between FnMut with &mut self and Fn with interior mutability by asking who owns the chain, whether dispatch is shared, and which threads call it.

for a principal

The handler bound and the dispatch receiver fix how a callback system can be shared later; changing Box<dyn FnMut> to Fn plus Sync after release breaks every handler author.

## Calling a stored closure through a reference A closure stored in a collection is usually boxed, because each closure has its own type and a `Vec` needs one element type. `Box<dyn FnMut(&Event)>` is a **trait object**: a pointer to the closure plus a vtable for its call method. Std implements the call traits for boxes, `FnMut` for `Box<F>` where `F: FnMut`, `Fn` for `Box<F>` where `F: Fn`, so calling the box calls the closure with the same receiver. | Stored handler type | Call needs | `dispatch` can take | Handler may mutate captures directly | |---|---|---|---| | `Box<dyn Fn(&Event)>` | `&` to the box | `&self` | no; only through `Cell`, `RefCell`, `Mutex` or atomics | | `Box<dyn FnMut(&Event)>` | `&mut` to the box | `&mut self` | yes | | `Box<dyn FnOnce(&Event)>` | ownership of the box | `self` or a `take()` | yes, but it runs only once | ## Why the loop is rejected `for h in &self.handlers` iterates `&Vec<Box<dyn FnMut(&Event)>>`, which yields `&Box<dyn FnMut(&Event)>`. Calling `h(e)` needs `&mut Box<...>`, and a mutable borrow cannot be made through a shared one. rustc 1.99 reports: - **E0596**, "cannot borrow `*h` as mutable, as it is behind a `&` reference"; - a label on the loop, "this iterator yields `&` references"; - help, "use a mutable iterator instead", suggesting `&mut self.handlers`. The same rule shows up without a `Vec`: `let c: Box<dyn FnMut()> = ...; c();` is E0596 because `c` is not declared `mut`. The binding, the field or the iterator has to provide unique access. ## Fix 1: keep `FnMut`, dispatch through `&mut self` 1. Change `fn dispatch(&self, e: &Event)` to `fn dispatch(&mut self, e: &Event)`. 2. Iterate with `self.handlers.iter_mut()` or `&mut self.handlers`, which yields `&mut Box<dyn FnMut(&Event)>`. 3. Accept handlers as `impl FnMut(&Event) + 'static` when registering, so callers can pass closures that push into a captured log or count requests, and `Fn` closures still fit. This is the most flexible bound for handler authors and costs nothing at run time. Its limit is the receiver: while `dispatch` holds `&mut self`, nothing else can touch the chain, so a handler cannot register another handler during dispatch, and a chain shared through `Rc` or `Arc` cannot be dispatched without a `RefCell` or a lock around it. ## Fix 2: store `Fn`, keep state in interior mutability 1. Store `Vec<Box<dyn Fn(&Event)>>` and dispatch from `&self`. 2. Handlers that need state capture a `Cell<u32>` for a counter, a `RefCell<Vec<String>>` for a log, or shared state through `Rc`. 3. When the chain is shared across threads, store `Box<dyn Fn(&Event) + Send + Sync>` and keep state in `Mutex` or atomics; `Cell` and `RefCell` are not `Sync`, which the lesson on Send and Sync covers. A closure that only calls `hits.set(hits.get() + 1)` on a captured `Cell` is `Fn`, because `Cell::set` takes `&self`. That is what lets it sit in a list of `Fn` handlers. ## Choosing between them - **One owner, sequential dispatch**: `FnMut` and `&mut self`. Handler authors write ordinary mutable code. - **Dispatch from a shared reference**, for example a chain behind `Arc` used by many request tasks: `Fn + Send + Sync`, with synchronised state. - **Re-entrant registration** during dispatch: neither borrow pattern allows mutating the `Vec` while iterating it; collect new handlers in a separate list and append them after the loop. The `'static` in `Box<dyn FnMut(&Event)>`, the default object lifetime that stops a handler from borrowing a local, belongs to the lesson on higher-ranked and `'static` bounds; this question is only about the receiver. ## Mistakes to avoid - Wrapping each handler in `RefCell<Box<dyn FnMut>>` to keep `&self`, when `&mut self` would do with no run-time borrow check. - Assuming `Box` gives its contents mutable access through a shared reference. - Downgrading handlers to `Fn` without giving them somewhere to keep state.

  • Why can a closure that does `hits.set(hits.get() + 1)` be stored as `Box<dyn Fn(&Event)>`?
    Because `Cell::set` and `Cell::get` take `&self`, so the closure only needs a shared borrow of the captured cell and never mutates the capture itself. The Reference's rule is about mutating or moving captured variables, and interior mutability does neither.
  • The chain is shared across request threads behind an `Arc`; what handler type do you store?
    `Box<dyn Fn(&Event) + Send + Sync>`. `Arc` hands out only shared references, so dispatch runs from `&self` and handlers must be `Fn`, and the chain must be `Sync` to be shared. State goes into a `Mutex` or atomics, since `Cell` and `RefCell` are not `Sync`.

  • Box gives a stored closure mutable access through a shared reference.
  • Fn handlers cannot keep any state between calls.
  • Store FnOnce handlers so each one can run on every event.
  • RefCell around each handler is the standard fix for E0596.
  • Arc lets threads call FnMut handlers without a lock.