Answer#
C has function pointers with a void *user_data argument, C# has event and delegates, Java has listener interfaces and lambdas, JavaScript has emitter.on("x", fn). All of them store code to run later, together with some state. In Rust that is a closure: it captures the variables it uses, and the type of the stored value is Box<dyn FnMut(&Event)> when you keep many different closures in one list.
Closures that only read use Fn, closures that change what they captured use FnMut, and closures that consume what they captured use FnOnce. The program has an event bus with two handlers (one counts clicks, one prints keys), and then handles the same events through a channel. It was compiled and run with rustc 1.93.0.
use std::sync::mpsc;
enum Event {
Click(i32, i32),
Key(char),
}
struct Bus {
handlers: Vec<Box<dyn FnMut(&Event)>>,
}
impl Bus {
fn subscribe(&mut self, f: impl FnMut(&Event) + 'static) {
self.handlers.push(Box::new(f));
}
fn emit(&mut self, e: Event) {
for h in &mut self.handlers {
h(&e);
}
}
}
fn main() {
let mut bus = Bus { handlers: Vec::new() };
let mut clicks = 0;
bus.subscribe(move |e| {
if let Event::Click(x, y) = e {
clicks += 1;
println!("click #{clicks} at {x},{y}");
}
});
bus.subscribe(|e| {
if let Event::Key(c) = e {
println!("key {c}");
}
});
bus.emit(Event::Click(3, 4));
bus.emit(Event::Key('q'));
bus.emit(Event::Click(5, 6));
// Alternative: no callbacks at all, events travel through a channel and one loop handles them.
let (tx, rx) = mpsc::channel();
tx.send(Event::Key('a')).unwrap();
tx.send(Event::Click(1, 1)).unwrap();
drop(tx);
for e in rx {
match e {
Event::Key(c) => println!("channel: key {c}"),
Event::Click(x, y) => println!("channel: click {x},{y}"),
}
}
}click #1 at 3,4
key q
click #2 at 5,6
channel: key a
channel: click 1,1The clicks counter is moved into the first closure (move) and changed by it, with no shared variable and no lock. That works because only that handler uses it. If two handlers must change the same value, the compiler will not let both borrow it mutably; you then choose between Rc<RefCell<T>> (one thread), Arc<Mutex<T>> (several threads), or the channel version, where handlers only produce messages and one place owns the state.
How to do it#
- Define the event as an
enum; each variant carries the data the old callback received. Avoid *becomes a captured variable or a generic type. - Store handlers as
Box<dyn FnMut(&Event)>(add+ Sendif they are called from other threads). - Move the state a handler needs into its closure with
move. - If handlers need to remove themselves or register others while running, collect those requests and apply them after the loop over handlers; the borrow checker will point out the places where that matters.
Common mistakes#
- Capturing
selfin a closure that is stored insideself. This is a cycle of ownership; pass the pieces of state the closure needs, or use a channel. - Forgetting
moveand getting "closure may outlive the current function" errors when the closure is stored or sent to a thread. - Using
Rc<RefCell<..>>everywhere to imitate the old shared mutable object. It compiles, but conflicting borrows then panic at run time.
Related questions#
How do I port a C function pointer that takes void *user_data?#
Inside Rust, a closure replaces both the function and the data. At an FFI boundary where C calls back, you still need an extern "C" fn; the C library's data pointer can carry a pointer to a boxed closure (a pattern not shown or run here). The thread on calling a C library shows a callback through an extern "C" fn.
Is a channel better than callbacks?#
It is a different design: handlers run where the receiving loop runs, state has one owner, and ordering is visible. It costs a copy or move of each message and adds a queue.
Sources#
- The Rust Book, "Closures": https://doc.rust-lang.org/book/ch13-01-closures.html
- The Rust Book, "Using Message Passing to Transfer Data Between Threads": https://doc.rust-lang.org/book/ch16-02-message-passing.html