Can you make a custom EventListener in Rust?

Say, I have a variable: let mut x: i32 = 5;, and this x gets changed to 10 in some function.

Is there, or can I make a trigger/EvenListener (like in JS) to 'do something' when x has changed? F.e.: x.onchange = () => { ... }?

No. You would need to build this yourself, e.g. make a wrapper struct that stores the value and a list of listeners, then define a set method that calls each listener.

That said, event listeners work pretty poorly in Rust due to the single ownership principle - event listeners normally require shared ownership, which is more cumbersome to work with.

Could you explain what you mean with list of listeners?

Well, you can store any function with the type Box<dyn FnMut(arguments)>.

struct I32WithEvents {
    value: i32,
    listeners: Vec<Box<dyn FnMut(i32, i32)>>,
}

You could also make your own trait:

trait I32Listener {
    fn on_update(&mut self, old_value: i32, new_value: i32);
}

struct I32WithEvents {
    value: i32,
    listeners: Vec<Box<dyn I32Listener>>,
}
1 Like

Thanks, this seems very usefull. I will need to look more into but this helps a lot