1 // Rust-101, Part 06: Copy, Lifetimes
2 // ==================================
4 // We continue to work on our `BigInt`, so we start by importing what we already established.
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`.
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() {
20 } else if self.data.len() > other.data.len() {
23 // **Exercise 06.1**: Fill in this code.
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.
36 min = Some(match min { /*@*/
38 Some(n) => e.min_try1(n) /*@*/
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?
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
59 //@ But before we go there, I should answer the second question I brought up above: Why did our old
60 //@ `vec_min` work? We stored the minimal `i32` locally without cloning, and Rust did not complain.
61 //@ That's because there isn't really much of an "ownership" when it comes to types like `i32` or
62 //@ `bool`: If you move the value from one place to another, then both instances are "complete". We
63 //@ also say the value has been *duplicated*. This is in stark contrast to types like `Vec<i32>`,
64 //@ where moving the value results in both the old and the new vector to point to the same
65 //@ underlying buffer. We don't have two vectors, there's no proper duplication.
67 //@ Rust calls types that can be easily duplicated `Copy` types. `Copy` is another trait, and it is
68 //@ implemented for types like `i32` and `bool`. Remember how we defined the trait `Minimum` by
69 //@ writing `trait Minimum : Copy { ...`? This tells Rust that every type that implements `Minimum`
70 //@ must also implement `Copy`, and that's why the compiler accepted our generic `vec_min` in part
71 //@ 02. `Copy` is the first *marker trait* that we encounter: It does not provide any methods, but
72 //@ 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.
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.
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.
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.
104 //@ The function `head` demonstrates how that could work: It returns a reference to the first
105 //@ element of a vector if it is non-empty. The type of the function says that it will either
106 //@ return nothing, or it will return a borrowed `T`. We can then obtain a reference to the first
107 //@ element of `v` and use it to construct the return value.
108 fn head<T>(v: &Vec<T>) -> Option<&T> {
115 // Technically, we are returning a pointer to the first element. But doesn't that mean that callers
116 // have to be careful? Imagine `head` would be a C++ function, and we would write the following
119 int foo(std::vector<int> v) {
120 int *first = head(v);
125 //@ This is very much like our very first motivating example for ownership, at the beginning of
126 //@ part 04: `push_back` could reallocate the buffer, making `first` an invalid pointer. Again, we
127 //@ have aliasing (of `first` and `v`) and mutation. But this time, the bug is hidden behind the
128 //@ call to `head`. How does Rust solve this? If we translate the code above to Rust, it doesn't
129 //@ compile, so clearly we are good - but how and why?
130 //@ (Notice that have to explicitly assert using //@ `unwrap` that `first` is not `None`, whereas
131 //@ the C++ code above would silently dereference a //@ `NULL`-pointer. But that's another point.)
132 fn rust_foo(mut v: Vec<i32>) -> i32 {
133 let first: Option<&i32> = head(&v);
138 //@ To give the answer to this question, we have to talk about the *lifetime* of a reference. The
139 //@ point is, saying that you borrowed your friend a `Vec<i32>`, or a book, is not good enough,
140 //@ unless you also agree on *how long* your friend can borrow it. After all, you need to know when
141 //@ you can rely on owning your data (or book) again.
143 //@ Every reference in Rust has an associated lifetime, written `&'a T` for a reference with
144 //@ lifetime `'a` to something of type `T`. The full type of `head` reads as follows: `fn<'a,
145 //@ T>(&'a Vec<T>) -> Option<&'a T>`. Here, `'a` is a *lifetime variable*, which represents for how
146 //@ long the vector has been borrowed. The function type expresses that argument and return value
147 //@ have *the same lifetime*.
149 //@ When analyzing the code of `rust_foo`, Rust has to assign a lifetime to `first`. It will choose
150 //@ the scope where `first` is valid, which is the entire rest of the function. Because `head` ties
151 //@ the lifetime of its argument and return value together, this means that `&v` also has to borrow
152 //@ `v` for the entire duration of the function `rust_foo`. So when we try to create a unique
153 //@ reference to `v` for `push`, Rust complains that the two references (the one for `head`, and
154 //@ the one for `push`) overlap, so neither of them can be unique. Lucky us! Rust caught our
155 //@ mistake and made sure we don't crash the program.
157 //@ So, to sum this up: Lifetimes enable Rust to reason about *how long* a reference is valid, how
158 //@ long ownership has been borrowed. We can thus safely write functions like `head`, that return
159 //@ references into data they got as argument, and make sure they are used correctly, *while
160 //@ looking only at the function type*. At no point in our analysis of `rust_foo` did we have to
161 //@ look *into* `head`. That's, of course, crucial if we want to separate library code from
162 //@ application code. Most of the time, we don't have to explicitly add lifetimes to function
163 //@ types. This is thanks to *lifetime elision*, where Rust will automatically insert lifetimes we
164 //@ did not specify, following some simple, well-documented
165 //@ [rules](https://doc.rust- lang.org/stable/book/lifetimes.html#lifetime-elision).
167 //@ [index](main.html) | [previous](part05.html) | [raw source](workspace/src/part06.rs) |
168 //@ [next](part07.html)