Created
July 15, 2016 22:24
-
-
Save vasi/be6d2de7acda1a163b26e4b1246d766c to your computer and use it in GitHub Desktop.
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
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