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