FAQ - Help and questions

How do I port callbacks, listeners and event handlers to Rust?

#porting#closures#eventspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A callback becomes a closure stored as Box<dyn FnMut(&Event)>, and a listener list becomes a Vec of those boxes. Captured state moves into the closure. When handlers need to change shared state or each other, send events through a channel to one loop instead, which avoids shared mutable state.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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}"),
        }
    }
}
text
click #1 at 3,4
key q
click #2 at 5,6
channel: key a
channel: click 1,1

The 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#

  1. Define the event as an enum; each variant carries the data the old callback received. A void * becomes a captured variable or a generic type.
  2. Store handlers as Box<dyn FnMut(&Event)> (add + Send if they are called from other threads).
  3. Move the state a handler needs into its closure with move.
  4. 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 self in a closure that is stored inside self. This is a cycle of ownership; pass the pieces of state the closure needs, or use a channel.
  • Forgetting move and 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet