Skip to content

Instantly share code, notes, and snippets.

@haudan
Created June 1, 2017 09:31
Show Gist options
  • Save haudan/91600350421d84d35b203fc6837019af to your computer and use it in GitHub Desktop.
Save haudan/91600350421d84d35b203fc6837019af to your computer and use it in GitHub Desktop.
A Rust data structure that can store closures and invoke them. A poor mans version of `event` from C#.
struct Event<'a> {
handlers: Vec<Box<FnMut() + 'a>>,
}
impl<'a> Event<'a> {
fn new() -> Self {
Self {
handlers: Vec::new(),
}
}
fn invoke(&mut self) {
for h in self.handlers.iter_mut() {
h();
}
}
fn add_handler<H: FnMut() + 'a>(&mut self, handler: H) {
self.handlers.push(Box::new(handler));
}
}
fn main() {
let mut main_event_fired = false;
let mut on_click_event = Event::new();
on_click_event.add_handler(|| {
if !main_event_fired {
println!("Hello world!");
main_event_fired = true;
}
});
on_click_event.add_handler(|| println!("Kewl!"));
on_click_event.invoke();
on_click_event.invoke();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment