Created
September 20, 2016 20:58
-
-
Save anonymous/704b4bd0c5bd3f810f9675377ae39289 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Manager { | |
callbacks: Vec<Box<FnMut()>>, | |
} | |
impl Manager { | |
fn new() -> Manager { | |
Manager { callbacks: Vec::new() } | |
} | |
fn register(&mut self, callback: Box<FnMut()>) { | |
self.callbacks.push(callback); | |
} | |
fn call(&mut self) { | |
for callback in &mut self.callbacks { | |
callback(); | |
} | |
} | |
} | |
struct Plugin { | |
counter: u32, | |
} | |
impl Plugin { | |
fn new() -> Plugin { | |
Plugin { counter: 0 } | |
} | |
fn increment(&mut self) { | |
println!("Increment"); | |
self.counter += 1; | |
} | |
fn get(&self) -> u32 { | |
self.counter | |
} | |
} | |
fn main() { | |
use std::rc::Rc; | |
use std::cell::RefCell; | |
let mut manager = Manager::new(); | |
manager.register(Box::new(|| { | |
println!("Hello!"); | |
})); | |
manager.register(Box::new(|| { | |
println!("Hola!"); | |
})); | |
let plugin = Rc::new(RefCell::new(Plugin::new())); | |
let rc = plugin.clone(); | |
manager.register(Box::new(move || { | |
rc.borrow_mut().increment(); | |
})); | |
let rc = plugin.clone(); | |
manager.register(Box::new(move || println!("Plugin: {}", rc.borrow().get()))); | |
manager.call(); | |
manager.call(); | |
manager.call(); | |
manager.call(); | |
manager.call(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment