Store FnMut Callbacks In A Box

Register heterogeneous closures in one Vec of Box<dyn FnMut> and fire them later, because boxed trait objects erase the distinct closure types.

RustData Integrity

Code

rustsnippet
33 lines
// 回调(callbacks)注册表:Box<dyn FnMut> 抹平不同闭包的类型差异
struct Hooks {
    on_event: Vec<Box<dyn FnMut(&str)>>,
}

impl Hooks {
    fn new() -> Self {
        Hooks { on_event: Vec::new() }
    }

    fn register(&mut self, f: impl FnMut(&str) + 'static) {
        self.on_event.push(Box::new(f));
    }

    fn fire(&mut self, event: &str) {
        for f in self.on_event.iter_mut() {
            f(event);
        }
    }
}

fn main() {
    let mut calls = 0;
    let mut hooks = Hooks::new();
    hooks.register(|e| println!("log: {e}"));
    hooks.register(move |e| {
        calls += 1;
        println!("count {calls}: {e}");
    });

    hooks.fire("deploy");
    hooks.fire("rollback");
}

How it works

Everything lives in one struct Hooks: new builds the empty Vec, register boxes each closure with Box::new, and fire walks self.on_event calling every stored callback; main wires it together.

for f in self.on_event.iter_mut() is the loop that carries the per-item work.

Applying it

fn new() -> Self returns Hooks { on_event: Vec::new() } — an empty registry ready for the register calls.

Each fire call drives both registered closures, so fire("deploy") prints log: deploy and then count 1: deploy — one labeled line per callback, with the counter reaching count 2 on the rollback pass.

Running the file executes main, which drives new, register and fire in order.

Statements that matter

fn register(&mut self, f: impl FnMut(&str) + 'static) {
self.on_event.push(Box::new(f));
}
fn fire(&mut self, event: &str) {
for f in self.on_event.iter_mut() {
f(event);
}
}
hooks.register(move |e| {
calls += 1;
println!("count {calls}: {e}");
});

Interactive Tools for This Topic

FAQ

What does Store FnMut Callbacks In A Box print when run?
Run it as a complete program — the output lines carry labels such as `log:`, `count`.