finish part 14
[rust-101.git] / src / part11.rs
1 // Rust-101, Part 11: Trait Objects, Box, Rc, Lifetime bounds
2 // ==========================================================
3
4 //@ We will play around with closures a bit more. Let us implement some kind of generic "callback"
5 //@ mechanism, providing two functions: Registering a new callback, and calling all registered callbacks. There will be two
6 //@ versions, so to avoid clashes of names, we put them into modules.
7 mod callbacks {
8     //@ First of all, we need to find a way to store the callbacks. Clearly, there will be a `Vec` involved, so that we can
9     //@ always grow the number of registered callbacks. A callback will be a closure, i.e., something implementing
10     //@ `FnMut(i32)` (we want to call this multiple times, so clearly `FnOnce` would be no good). So our first attempt may be the following.
11     // For now, we just decide that the callbacks have an argument of type `i32`.
12     struct CallbacksV1<F: FnMut(i32)> {
13         callbacks: Vec<F>,
14     }
15     //@ However, this will not work. Remember how the "type" of a closure is specific to the environment of captured variables. Different closures
16     //@ all implementing `FnMut(i32)` may have different types. However, a `Vec<F>` is a *uniformly typed* vector.
17
18     //@ We will thus need a way to store things of *different* types in the same vector. We know all these types implement `FnMut(i32)`. For this scenario,
19     //@ Rust provides *trait objects*: The truth is, `FnMut(i32)` is not just a trait. It is also a type, that can be given to anything implementing
20     //@ this trait. So, we may write the following.
21     /* struct CallbacksV2 {
22         callbacks: Vec<FnMut(i32)>,
23     } */
24     //@ But, Rust complains about this definition. It says something about "Sized". What's the trouble? See, for many things we want to do, it is crucial that
25     //@ Rust knows the precise, fixed size of the type - that is, how large this type will be when represented in memory. For example, for a `Vec`, the
26     //@ elements are stored one right after the other. How should that be possible, without a fixed size? The trouble is, `FnMut(i32)` could be of any size.
27     //@ We don't know how large that "type that implemenets `FnMut(i32)`" is. Rust calls this an *unsized* type. Whenever we introduce a type variable, Rust
28     //@ will implicitly add a bound to that variable, demanding that it is sized. That's why we did not have to worry about this so far. <br/>
29     //@ You can opt-out of this implicit bound by saying `T: ?Sized`. Then `T` may or may not be sized.
30
31     //@ So, what can we do, if we can't store the callbacks in a vector? We can put them in a box. Semantically, `Box<T>` is a lot like `T`: You fully own
32     //@ the data stored there. On the machine, however, `Box<T>` is a *pointer* to `T`. It is a lot like `std::unique_ptr` in C++. In our current example,
33     //@ the important bit is that since it's a pointer, `T` can be unsized, but `Box<T>` itself will always be sized. So we can put it in a `Vec`.
34     pub struct Callbacks {
35         callbacks: Vec<Box<FnMut(i32)>>,
36     }
37
38     impl Callbacks {
39         // Now we can provide some functions. The constructor should be straight-forward.
40         pub fn new() -> Self {
41             Callbacks { callbacks: Vec::new() }                     /*@*/
42         }
43
44         // Registration simply stores the callback.
45         pub fn register(&mut self, callback: Box<FnMut(i32)>) {
46             self.callbacks.push(callback);                          /*@*/
47         }
48
49         // And here we call all the stored callbacks.
50         pub fn call(&mut self, val: i32) {
51             // Since they are of type `FnMut`, we need to mutably iterate. Notice that boxes dereference implicitly.
52             for callback in self.callbacks.iter_mut() {
53                 callback(val);                                      /*@*/
54             }
55         }
56     }
57
58     // Now we are ready for the demo.
59     pub fn demo(c: &mut Callbacks) {
60         c.register(Box::new(|val| println!("Callback 1: {}", val)));
61         c.call(0);
62
63         //@ We can even register callbacks that modify their environment. Rust will again attempt to borrow `count`. However,
64         //@ that doesn't work out this time: Since we want to put this thing in a `Box`, it could live longer than the function
65         //@ we are in. Then the borrow of `count` would become invalid. We have to explicitly tell Rust to `move` ownership of the
66         //@ variable into the closure. Its environment will then contain a `usize` rather than a `&mut uszie`, and have
67         //@ no effect on this local variable anymore.
68         let mut count: usize = 0;
69         c.register(Box::new(move |val| {
70             count = count+1;
71             println!("Callback 2, {}. time: {}", count, val);
72         } ));
73         c.call(1); c.call(2);
74     }
75 }
76
77 // Remember to edit `main.rs` to run the demo.
78 pub fn main() {
79     let mut c = callbacks::Callbacks::new();
80     callbacks::demo(&mut c);
81 }
82
83 mod callbacks_clone {
84     //@ So, this worked great, didn't it! There's one point though that I'd like to emphasize: One cannot `clone` a closure.
85     //@ Hence it becomes impossible to implement `Clone` for our `Callbacks` type. What could we do about this?
86
87     //@ You already learned about `Box` above. `Box` is an example of a *smart pointer*: It's like a pointer (in the C
88     //@ sense), but with some additional smarts to it. For `Box`, that's the part about ownership. Once you drop the box, the
89     //@ content it points to will be deleted. <br/>
90     //@ Another example of a smart pointer is `Rc<T>`. This is short for *reference-counter*, so you can already guess how
91     //@ this pointer is smart: It has a reference count. You can `clone` an `Rc` as often as you want, that doesn't affect the
92     //@ data it contains at all. It only creates more references to the same data. Once all the references are gone, the data is deleted.
93     //@ 
94     //@ Wait a moment, you may say here. Multiple references to the same data? That's aliasing! Indeed:
95     //@ Once data is stored in an `Rc`, it is read-only. By dereferencing the smart `Rc`, you can only get a shared borrow of the data.
96     use std::rc::Rc;
97
98     //@ Because of this read-only restriction, we cannot use `FnMut` here: We'd be unable to call the function with a mutable borrow
99     //@ of it's environment! So we have to go with `Fn`. We wrap that in an `Rc`, and then Rust happily derives `Clone` for us.
100     #[derive(Clone)]
101     pub struct Callbacks {
102         callbacks: Vec<Rc<Fn(i32)>>,
103     }
104
105     impl Callbacks {
106         pub fn new() -> Self {
107             Callbacks { callbacks: Vec::new() }                     /*@*/
108         }
109
110         // For the `register` function, we don't actually have to use trait objects in the argument.
111         //@ We can make this function generic, such that it will be instantiated with some concrete closure type `F`
112         //@ and do the creation of the `Rc` and the conversion to `Fn(i32)` itself.
113         
114         //@ For this to work, we need to demand that the type `F` does not contain any short-lived borrows. After all, we will store it
115         //@ in our list of callbacks indefinitely. If the closure contained a pointer to our caller's stackframe, that pointer
116         //@ could be invalid by the time the closure is called. We can mitigate this by bounding `F` by a *lifetime*: `T: 'a` says
117         //@ that all data of type `T` will *outlive* (i.e., will be valid for at least as long as) lifetime `'a`.
118         //@ Here, we use the special lifetime `'static`, which is the lifetime of the entire program.
119         //@ The same bound has been implicitly added in the version of `register` above, and in the definition of
120         //@ `Callbacks`. This is the reason we could not have the borrowed `count` in the closure in `demo` previously.
121         pub fn register<F: Fn(i32)+'static>(&mut self, callback: F) {
122             self.callbacks.push(Rc::new(callback));             /*@*/
123         }
124
125         pub fn call(&mut self, val: i32) {
126             // We only need a shared iterator here. `Rc` also implicitly dereferences, so we can simply call the callback.
127             for callback in self.callbacks.iter() {
128                 callback(val);                                      /*@*/
129             }
130         }
131     }
132
133     // The demo works just as above. Our counting callback doesn't work anymore though, because we are using `Fn` now.
134     fn demo(c: &mut Callbacks) {
135         c.register(|val| println!("Callback 1: {}", val));
136         c.call(0); c.call(1);
137     }
138 }
139
140 // **Exercise 11.1**: We made the arbitrary choice of using `i32` for the arguments. Generalize the data-structures above
141 // to work with an arbitrary type `T` that's passed to the callbacks. Since you need to call multiple callbacks with the
142 // same `t: T`, you will either have to restrict `T` to `Copy` types, or pass a borrow.
143
144 //@ ## Run-time behavior
145 //@ When you run the program above, how does Rust know what to do with the callbacks? Since an unsized type lacks some information,
146 //@ a *pointer* to such a type (be it a `Box`, an `Rc` or a borrow) will need to complete this information. We say that pointers to
147 //@ trait objects are *fat*. They store not only the address of the object, but (in the case of trait objects) also a *vtable*: A
148 //@ table of function pointers, determining the code that's run when a trait method is called. There are some restrictions for traits to be usable
149 //@ as trait objects. This is called *object safety* and described in [the documentation](http://doc.rust-lang.org/stable/book/trait-objects.html) and [the reference](http://doc.rust-lang.org/reference.html#trait-objects).
150 //@ 
151 //@ Whenever you write a generic function, you have a choice: You can make it polymorphic, like our `vec_min`. Or you
152 //@ can use trait objects, like the first `register` above. The latter will result in only a single compiled version (rather
153 //@ than one version per type it is instantiated with). This makes for smaller code, but you pay the overhead of the virtual function calls.
154 //@ Isn't it beautiful how traits can handle both of these cases (and much more, as we saw, like closures and operator overloading) nicely?
155
156 //@ [index](main.html) | [previous](part10.html) | [next](part12.html)