1 // Rust-101, Part 11: Trait Objects, Box, Rc, Lifetime bounds
2 // ==========================================================
5 // For now, we just decide that the callbacks have an argument of type `i32`.
6 struct CallbacksV1<F: FnMut(i32)> {
10 /* struct CallbacksV2 {
11 callbacks: Vec<FnMut(i32)>,
14 pub struct Callbacks {
15 callbacks: Vec<Box<FnMut(i32)>>,
19 // Now we can provide some functions. The constructor should be straight-forward.
20 pub fn new() -> Self {
24 // Registration simply stores the callback.
25 pub fn register(&mut self, callback: Box<FnMut(i32)>) {
29 // And here we call all the stored callbacks.
30 pub fn call(&mut self, val: i32) {
31 // Since they are of type `FnMut`, we need to mutably iterate. Notice that boxes dereference implicitly.
32 for callback in self.callbacks.iter_mut() {
38 // Now we are ready for the demo.
39 pub fn demo(c: &mut Callbacks) {
40 c.register(Box::new(|val| println!("Callback 1: {}", val)));
43 let mut count: usize = 0;
44 c.register(Box::new(move |val| { count = count+1; println!("Callback 2, {}. time: {}", count, val); } ));
49 // Remember to edit `main.rs` to run the demo.
51 let mut c = callbacks::Callbacks::new();
52 callbacks::demo(&mut c);
60 pub struct Callbacks {
61 callbacks: Vec<Rc<Fn(i32)>>,
65 pub fn new() -> Self {
69 // For the `register` function, we don't actually have to use trait objects in the argument.
71 pub fn register<F: Fn(i32)+'static>(&mut self, callback: F) {
75 pub fn call(&mut self, val: i32) {
76 // We only need a shared iterator here. `Rc` also implicitly dereferences, so we can simply call the callback.
77 for callback in self.callbacks.iter() {
83 // The demo works just as above. Our counting callback doesn't work anymore though, because we are using `Fn` now.
84 fn demo(c: &mut Callbacks) {
85 c.register(|val| println!("Callback 1: {}", val));
90 // **Exercise 11.1**: We made the arbitrary choice of using `i32` for the arguments. Generalize the data-structures above
91 // to work with an arbitrary type `T` that's passed to the callbacks. Since you need to call multiple callbacks with the
92 // same `t: T`, you will either have to restrict `T` to `Copy` types, or pass a borrow.