remove workspace from the repository, instead generate a zipfile to upload
[rust-101.git] / src / part11.rs
1 // Rust-101, Part 11: Trait Objects, Box, 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.
6
7 //@ First of all, we need to find a way to store the callbacks. Clearly, there will be a `Vec` involved, so that we can
8 //@ always grow the number of registered callbacks. A callback will be a closure, i.e., something implementing
9 //@ `FnMut(i32)` (we want to call this multiple times, so clearly `FnOnce` would be no good). So our first attempt may be the following.
10 // For now, we just decide that the callbacks have an argument of type `i32`.
11 struct CallbacksV1<F: FnMut(i32)> {
12     callbacks: Vec<F>,
13 }
14 //@ However, this will not work. Remember how the "type" of a closure is specific to the environment of captured variables. Different closures
15 //@ all implementing `FnMut(i32)` may have different types. However, a `Vec<F>` is a *uniformly typed* vector.
16
17 //@ 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,
18 //@ 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
19 //@ this trait. So, we may write the following.
20 /* struct CallbacksV2 {
21     callbacks: Vec<FnMut(i32)>,
22 } */
23 //@ 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
24 //@ 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
25 //@ elements are stored one right after the other. How should that be possible, without a fixed size? The point is, `FnMut(i32)` could be of any size.
26 //@ 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
27 //@ 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/>
28 //@ You can opt-out of this implicit bound by saying `T: ?Sized`. Then `T` may or may not be sized.
29
30 //@ 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
31 //@ the data stored there. On the machine, however, `Box<T>` is a *pointer* to a heap-allocated `T`. It is a lot like `std::unique_ptr` in C++. In our current example,
32 //@ 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`.
33 pub struct Callbacks {
34     callbacks: Vec<Box<FnMut(i32)>>,
35 }
36
37 impl Callbacks {
38     // Now we can provide some functions. The constructor should be straight-forward.
39     pub fn new() -> Self {
40         Callbacks { callbacks: Vec::new() }                         /*@*/
41     }
42
43     // Registration simply stores the callback.
44     pub fn register(&mut self, callback: Box<FnMut(i32)>) {
45         self.callbacks.push(callback);
46     }
47
48     // We can also write a generic version of `register`, such that it will be instantiated with some concrete closure type `F`
49     // and do the creation of the `Box` and the conversion from `F` to `FnMut(i32)` itself.
50     
51     //@ For this to work, we need to demand that the type `F` does not contain any short-lived references. After all, we will store it
52     //@ in our list of callbacks indefinitely. If the closure contained a pointer to our caller's stackframe, that pointer
53     //@ could be invalid by the time the closure is called. We can mitigate this by bounding `F` by a *lifetime*: `F: 'a` says
54     //@ that all data of type `F` will *outlive* (i.e., will be valid for at least as long as) lifetime `'a`.
55     //@ Here, we use the special lifetime `'static`, which is the lifetime of the entire program.
56     //@ The same bound has been implicitly added in the version of `register` above, and in the definition of
57     //@ `Callbacks`.
58     pub fn register_generic<F: FnMut(i32)+'static>(&mut self, callback: F) {
59         self.callbacks.push(Box::new(callback));                    /*@*/
60     }
61
62     // And here we call all the stored callbacks.
63     pub fn call(&mut self, val: i32) {
64         // Since they are of type `FnMut`, we need to mutably iterate.
65         for callback in self.callbacks.iter_mut() {
66             //@ Here, `callback` has type `&mut Box<FnMut(i32)>`. We can make use of the fact that `Box` is a *smart pointer*: In
67             //@ particular, we can use it as if it were a normal reference, and use `*` to get to its contents. Then we obtain a
68             //@ mutable reference to these contents, because we call a `FnMut`.
69             (&mut *callback)(val);                                  /*@*/
70             //@ Just like it is the case with normal references, this typically happens implicitly with smart pointers, so we can also directly call the function.
71             //@ Try removing the `&mut *`.
72             //@ 
73             //@ The difference to a reference is that `Box` implies full ownership: Once you drop the box (i.e., when the entire `Callbacks` instance is
74             //@ dropped), the content it points to on the heap will be deleted.
75         }
76     }
77 }
78
79 // Now we are ready for the demo. Remember to edit `main.rs` to run it.
80 pub fn main() {
81     let mut c = Callbacks::new();
82     c.register(Box::new(|val| println!("Callback 1: {}", val)));
83     c.call(0);
84
85     {
86         //@ We can even register callbacks that modify their environment. Per default, Rust will attempt to capture a reference to `count`, to borrow it. However,
87         //@ that doesn't work out this time. Remember the `'static` bound above? Borrowing `count` in the environment would
88         //@ violate that bound, as the reference is only valid for this block. If the callbacks are triggered later, we'd be in trouble.
89         //@ We have to explicitly tell Rust to `move` ownership of the variable into the closure. Its environment will then contain a
90         //@ `usize` rather than a `&mut usize`, and the closure has no effect on this local variable anymore.
91         let mut count: usize = 0;
92         c.register_generic(move |val| {
93             count = count+1;
94             println!("Callback 2: {} ({}. time)", val, count);
95         } );
96     }
97     c.call(1); c.call(2);
98 }
99
100 //@ ## Run-time behavior
101 //@ When you run the program above, how does Rust know what to do with the callbacks? Since an unsized type lacks some information,
102 //@ a *pointer* to such a type (be it a `Box` or a reference) will need to complete this information. We say that pointers to
103 //@ trait objects are *fat*. They store not only the address of the object, but (in the case of trait objects) also a *vtable*: A
104 //@ 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
105 //@ as trait objects. This is called *object safety* and described in [the documentation](https://doc.rust-lang.org/stable/book/trait-objects.html) and [the reference](https://doc.rust-lang.org/reference.html#trait-objects).
106 //@ In case of the `FnMut` trait, there's only a single action to be performed: Calling the closure. You can thus think of a pointer to `FnMut` as
107 //@ a pointer to the code, and a pointer to the environment. This is how Rust recovers the typical encoding of closures as a special case of a more
108 //@ general concept.
109 //@ 
110 //@ Whenever you write a generic function, you have a choice: You can make it generic, like `register_generic`. Or you
111 //@ can use trait objects, like `register`. The latter will result in only a single compiled version (rather
112 //@ than one version per type it is instantiated with). This makes for smaller code, but you pay the overhead of the virtual function calls.
113 //@ (Of course, in the case of `register` above, there's no function called on the trait object.)
114 //@ Isn't it beautiful how traits can nicely handle this tradeoff (and much more, as we saw, like closures and operator overloading)?
115
116 // **Exercise 11.1**: We made the arbitrary choice of using `i32` for the arguments. Generalize the data structures above
117 // to work with an arbitrary type `T` that's passed to the callbacks. Since you need to call multiple callbacks with the
118 // same `t: T`, you will either have to restrict `T` to `Copy` types, or pass a reference.
119
120 //@ [index](main.html) | [previous](part10.html) | [raw source](workspace/src/part11.rs) | [next](part12.html)