Skip to content

Instantly share code, notes, and snippets.

@vasi
Created July 15, 2016 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasi/be6d2de7acda1a163b26e4b1246d766c to your computer and use it in GitHub Desktop.
Save vasi/be6d2de7acda1a163b26e4b1246d766c to your computer and use it in GitHub Desktop.
use std::rc::Rc;
use std::cell::RefCell;
use std::ops::DerefMut;
struct A<'a> {
pub v: Vec<Rc<RefCell<FnMut() + 'a>>>,
}
impl<'a> A<'a> {
pub fn add3<F: FnMut() + 'a>(&mut self, f: F) {
let r = Rc::new(RefCell::new(f));
self.v.push(r.clone());
self.v.push(r.clone());
self.v.push(r.clone());
}
pub fn run(&mut self) {
for f in &mut self.v {
f.borrow_mut().deref_mut()();
}
}
}
fn main() {
let mut s = String::new();
{
let mut a = A { v: Vec::new() };
a.add3(|| {
s.push_str("foo");
});
a.run();
}
println!("{}", s); // "foofoofoo"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment