remove workspace from the repository, instead generate a zipfile to upload
[rust-101.git] / src / part06.rs
1 // Rust-101, Part 06: Copy, Lifetimes
2 // ==================================
3
4 // We continue to work on our `BigInt`, so we start by importing what we already established.
5 use part05::BigInt;
6
7 // With `BigInt` being about numbers, we should be able to write a version of `vec_min`
8 // that computes the minimum of a list of `BigInt`. First, we have to write `min` for `BigInt`.
9 impl BigInt {
10     fn min_try1(self, other: Self) -> Self {
11         //@ Just to be sure, we first check that both operands actually satisfy our invariant. `debug_assert!` is a
12         //@ macro that checks that its argument (must be of type `bool`) is `true`, and panics otherwise. It gets
13         //@ removed in release builds, which you do with `cargo build --release`.
14         debug_assert!(self.test_invariant() && other.test_invariant());
15         // Now our assumption of having no trailing zeros comes in handy:
16         // If the lengths of the two numbers differ, we already know which is larger.
17         if self.data.len() < other.data.len() {
18             self
19         } else if self.data.len() > other.data.len() {
20             other
21         } else {
22             // **Exercise 06.1**: Fill in this code.
23             unimplemented!()
24         }
25     }
26 }
27
28 // Now we can write `vec_min`.
29 fn vec_min(v: &Vec<BigInt>) -> Option<BigInt> {
30     let mut min: Option<BigInt> = None;
31     // If `v` is a shared reference to a vector, then the default for iterating over it is to call `iter`, the iterator that borrows the elements.
32     for e in v {
33         let e = e.clone();
34         min = Some(match min {                                      /*@*/
35             None => e,                                              /*@*/
36             Some(n) => e.min_try1(n)                                /*@*/
37         });                                                         /*@*/
38     }
39     min
40 }
41 //@ Now, what's happening here? Why do we have to to make a full (deep) copy of `e`, and why did we not
42 //@ have to do that in our previous version?
43 //@ 
44 //@ The answer is already hidden in the type of `vec_min`: `v` is just borrowed, but
45 //@ the Option<BigInt> that it returns is *owned*. We can't just return one of the elements of `v`,
46 //@ as that would mean that it is no longer in the vector! In our code, this comes up when we update
47 //@ the intermediate variable `min`, which also has type `Option<BigInt>`. If you replace get rid of the
48 //@ `e.clone()`, Rust will complain "Cannot move out of borrowed content". That's because
49 //@ `e` is a `&BigInt`. Assigning `min = Some(*e)` works just like a function call: Ownership of the
50 //@ underlying data is transferred from `e` to `min`. But that's not allowed, since
51 //@ we just borrowed `e`, so we cannot empty it! We can, however, call `clone` on it. Then we own
52 //@ the copy that was created, and hence we can store it in `min`. <br/>
53 //@ Of course, making such a full copy is expensive, so we'd like to avoid it. We'll come to that in the next part.
54
55 // ## `Copy` types
56 //@ But before we go there, I should answer the second question I brought up above: Why did our old `vec_min` work?
57 //@ We stored the minimal `i32` locally without cloning, and Rust did not complain. That's because there isn't
58 //@ really much of an "ownership" when it comes to types like `i32` or `bool`: If you move the value from one
59 //@ place to another, then both instances are "complete". We also say the value has been *duplicated*. This is in
60 //@ stark contrast to types like `Vec<i32>`, where moving the value results in both the old and the new vector to
61 //@ point to the same underlying buffer. We don't have two vectors, there's no proper duplication.
62 //@
63 //@ Rust calls types that can be easily duplicated `Copy` types. `Copy` is another trait, and it is implemented for
64 //@ types like `i32` and `bool`. Remember how we defined the trait `Minimum` by writing `trait Minimum : Copy { ...`?
65 //@ This tells Rust that every type that implements `Minimum` must also implement `Copy`, and that's why the compiler
66 //@ accepted our generic `vec_min` in part 02. `Copy` is the first *marker trait* that we encounter: It does not provide
67 //@ any methods, but makes a promise about the behavior of the type - in this case, being duplicable.
68
69 //@ If you try to implement `Copy` for `BigInt`, you will notice that Rust
70 //@ does not let you do that. A type can only be `Copy` if all its elements
71 //@ are `Copy`, and that's not the case for `BigInt`. However, we can make
72 //@ `SomethingOrNothing<T>` copy if `T` is `Copy`.
73 use part02::{SomethingOrNothing,Something,Nothing};
74 impl<T: Copy> Copy for SomethingOrNothing<T> {}
75 //@ Again, Rust can generate implementations of `Copy` automatically. If
76 //@ you add `#[derive(Copy,Clone)]` right before the definition of `SomethingOrNothing`,
77 //@ both `Copy` and `Clone` will automatically be implemented.
78
79 //@ ## An operational perspective
80 //@ Instead of looking at what happens "at the surface" (i.e., visible in Rust), one can also explain
81 //@ ownership passing and how `Copy` and `Clone` fit in by looking at what happens on the machine. <br/>
82 //@ When Rust code is executed, passing a value (like `i32` or `Vec<i32>`) to a function will always
83 //@ result in a shallow copy being performed: Rust just copies the bytes representing that value, and
84 //@ considers itself done. That's just like the default copy constructor in C++. Rust, however, will
85 //@ consider this a destructive operation: After copying the bytes elsewhere, the original value must
86 //@ no longer be used. After all, the two could now share a pointer! If, however, you mark a type `Copy`,
87 //@ then Rust will *not* consider a move destructive, and just like in C++, the old and new value
88 //@ can happily coexist. Now, Rust does not allow you to overload the copy constructor. This means that
89 //@ passing a value around will always be a fast operation, no allocation or any other kind of heap access
90 //@ will happen. In the situations where you would write a copy constructor in C++ (and hence
91 //@ incur a hidden cost on every copy of this type), you'd have the type *not* implement `Copy`, but only
92 //@ `Clone`. This makes the cost explicit.
93
94 // ## Lifetimes
95 //@ To fix the performance problems of `vec_min`, we need to avoid using `clone`. We'd like
96 //@ the return value to not be owned (remember that this was the source of our need for cloning), but *borrowed*.
97 //@ In other words, we want to return a shared reference to the minimal element.
98
99 //@ The function `head` demonstrates how that could work: It returns a reference to the first element of a vector if it is non-empty.
100 //@ The type of the function says that it will either return nothing, or it will return a borrowed `T`.
101 //@ We can then obtain a reference to the first element of `v` and use it to construct the return value.
102 fn head<T>(v: &Vec<T>) -> Option<&T> {
103     if v.len() > 0 {
104         Some(&v[0])                                                 /*@*/
105     } else {
106         None
107     }
108 }
109 // Technically, we are returning a pointer to the first element. But doesn't that mean that callers have to be
110 // careful? Imagine `head` would be a C++ function, and we would write the following code.
111 /*
112   int foo(std::vector<int> v) {
113     int *first = head(v);
114     v.push_back(42);
115     return *first;
116   }
117 */
118 //@ This is very much like our very first motivating example for ownership, at the beginning of part 04:
119 //@ `push_back` could reallocate the buffer, making `first` an invalid pointer. Again, we have aliasing (of `first`
120 //@ and `v`) and mutation. But this time, the bug is hidden behind the call to `head`. How does Rust solve this? If we translate
121 //@ the code above to Rust, it doesn't compile, so clearly we are good - but how and why?
122 //@ (Notice that have to explicitly assert using `unwrap` that `first` is not `None`, whereas the C++ code
123 //@ above would silently dereference a `NULL`-pointer. But that's another point.)
124 fn rust_foo(mut v: Vec<i32>) -> i32 {
125     let first: Option<&i32> = head(&v);
126     /* v.push(42); */
127     *first.unwrap()
128 }
129
130 //@ To give the answer to this question, we have to talk about the *lifetime* of a reference. The point is, saying that
131 //@ you borrowed your friend a `Vec<i32>`, or a book, is not good enough, unless you also agree on *how long*
132 //@ your friend can borrow it. After all, you need to know when you can rely on owning your data (or book) again.
133 //@ 
134 //@ Every reference in Rust has an associated lifetime, written `&'a T` for a reference with lifetime `'a` to something of type `T`. The full
135 //@ type of `head` reads as follows: `fn<'a, T>(&'a Vec<T>) -> Option<&'a T>`. Here, `'a` is a *lifetime variable*, which
136 //@ represents for how long the vector has been borrowed. The function type expresses that argument and return value have *the same lifetime*.
137 //@ 
138 //@ When analyzing the code of `rust_foo`, Rust has to assign a lifetime to `first`. It will choose the scope
139 //@ where `first` is valid, which is the entire rest of the function. Because `head` ties the lifetime of its
140 //@ argument and return value together, this means that `&v` also has to borrow `v` for the entire duration of
141 //@ the function `rust_foo`. So when we try to create a unique reference to `v` for `push`, Rust complains that the two references (the one
142 //@ for `head`, and the one for `push`) overlap, so neither of them can be unique. Lucky us! Rust caught our mistake and made sure we don't crash the program.
143 //@ 
144 //@ So, to sum this up: Lifetimes enable Rust to reason about *how long* a reference is valid, how long ownership has been borrowed. We can thus
145 //@ safely write functions like `head`, that return references into data they got as argument, and make sure they
146 //@ are used correctly, *while looking only at the function type*. At no point in our analysis of `rust_foo` did
147 //@ we have to look *into* `head`. That's, of course, crucial if we want to separate library code from application code.
148 //@ Most of the time, we don't have to explicitly add lifetimes to function types. This is thanks to *lifetime elision*,
149 //@ where Rust will automatically insert lifetimes we did not specify, following some [simple, well-documented rules](https://doc.rust-lang.org/stable/book/lifetimes.html#lifetime-elision).
150
151 //@ [index](main.html) | [previous](part05.html) | [raw source](workspace/src/part06.rs) | [next](part07.html)