Fixes as per review.
[rust-101.git] / src / part04.rs
1 // Rust-101, Part 04: Ownership, Borrowing, References
2 // ===================================================
3
4 //@ Rust aims to be a "safe systems language". As a systems language, of course it
5 //@ provides *references* (or *pointers*). But as a safe language, it has to
6 //@ prevent bugs like this C++ snippet.
7 /*
8   void foo(std::vector<int> v) {
9       int *first = &v[0];
10       v.push_back(42);
11       *first = 1337; // This is bad!
12   }
13 */
14 //@ What's going wrong here? `first` is a pointer into the vector `v`. The operation `push_back`
15 //@ may re-allocate the storage for the vector, in case the old buffer was full. If that happens,
16 //@ `first` is now a dangling pointer, and accessing it can crash the program (or worse).
17 //@ 
18 //@ It turns out that only the combination of two circumstances can lead to such a bug:
19 //@ *aliasing* and *mutation*. In the code above, we have `first` and the buffer of `v`
20 //@ being aliases, and when `push_back` is called, the latter is used to perform a mutation.
21 //@ Therefore, the central principle of the Rust typesystem is to *rule out mutation in the presence
22 //@ of aliasing*. The core tool to achieve that is the notion of *ownership*.
23
24 // ## Ownership
25 //@ What does that mean in practice? Consider the following example.
26 fn work_on_vector(v: Vec<i32>) { /* do something */ }
27 fn ownership_demo() {
28     let v = vec![1,2,3,4];
29     work_on_vector(v);
30     /* println!("The first element is: {}", v[0]); */               /* BAD! */
31 }
32 //@ Rust attaches additional meaning to the argument of `work_on_vector`: The function can assume
33 //@ that it entirely *owns* `v`, and hence can do anything with it. When `work_on_vector` ends,
34 //@ nobody needs `v` anymore, so it will be deleted (including its buffer on the heap).
35 //@ Passing a `Vec<i32>` to `work_on_vector` is considered *transfer of ownership*: Someone used
36 //@ to own that vector, but now he gave it on to `take` and has no business with it anymore.
37 //@ 
38 //@ If you give a book to your friend, you cannot just come to his place next day and get the book!
39 //@ It's no longer yours. Rust makes sure you don't break this rule. Try enabling the commented
40 //@ line in `ownership_demo`. Rust will tell you that `v` has been *moved*, which is to say that
41 //@ ownership has been transferred somewhere else. In this particular case, the buffer storing the
42 //@ data does not even exist anymore, so we are lucky that Rust caught this problem!
43 //@ Essentially, ownership rules out aliasing, hence making the kind of problem discussed above
44 //@ impossible.
45
46 // ## Borrowing a shared reference
47 //@ If you go back to our example with `vec_min`, and try to call that function twice, you will
48 //@ get the same error. That's because `vec_min` demands that the caller transfers ownership of the
49 //@ vector. Hence, when `vec_min` finishes, the entire vector is deleted. That's of course not what
50 //@ we wanted! Can't we somehow give `vec_min` access to the vector, while retaining ownership of it?
51 //@ 
52 //@ Rust calls this *a reference* to the vector, and it considers references as *borrowing*
53 //@ ownership. This works a bit like borrowing does in the real world: If your friend borrows a
54 //@ book from you, your friend can have it and work on it (and you can't!) as long as the book is
55 //@ still borrowed. Your friend could even lend the book to someone else. Eventually however, your
56 //@ friend has to give the book back to you, at which point you again have full control.
57 //@ 
58 //@ Rust distinguishes between two kinds of references. First of all, there's the *shared* reference.
59 //@ This is where the book metaphor kind of breaks down... you can give a shared reference to
60 //@ *the same data* to lots of different people, who can all access the data. This of course
61 //@ introduces aliasing, so in order to live up to its promise of safety, Rust generally does not
62 //@ allow mutation through a shared reference.
63
64 //@ So, let's re-write `vec_min` to work on a shared reference to a vector, written `&Vec<i32>`.
65 //@ I also took the liberty to convert the function from `SomethingOrNothing` to the standard
66 //@ library type `Option`.
67 fn vec_min(v: &Vec<i32>) -> Option<i32> {
68     use std::cmp;
69
70     let mut min = None;
71     // This time, we explicitly request an iterator for the vector `v`. The method `iter` just
72     // borrows the vector it works on, and provides shared references to the elements.
73     for e in v.iter() {
74         // In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
75         min = Some(match min {
76             None => *e,
77             Some(n) => cmp::min(n, *e)
78         });
79     }
80     min
81 }
82
83 // Now that `vec_min` does not acquire ownership of the vector anymore, we can call it multiple times on the same vector and also do things like
84 fn shared_ref_demo() {
85     let v = vec![5,4,3,2,1];
86     let first = &v[0];
87     vec_min(&v);
88     vec_min(&v);
89     println!("The first element is: {}", *first);
90 }
91 //@ What's going on here? First, `&` is how you lend ownership to someone - this operator creates a
92 //@ shared reference. `shared_ref_demo` creates three shared references to `v`: The reference
93 //@ `first` begins in the 2nd line of the function and lasts all the way to the end. The other two
94 //@ references, created for calling `vec_min`, only last for the duration of that respective call.
95 //@ 
96 //@ Technically, of course, references are pointers. Notice that since `vec_min` only gets a shared
97 //@ reference, Rust knows that it cannot mutate `v`. Hence the pointer into the buffer of `v`
98 //@ that was created before calling `vec_min` remains valid.
99
100 // ## Unique, mutable references
101 //@ There is a second way to borrow something, a second kind of reference: The *mutable reference*.
102 //@ This is a reference that comes with the promise that nobody else has *any kind of access* to
103 //@ the referee - in contrast to shared references, there is no aliasing with mutable references.
104 //@ It is thus always safe to perform mutation through such a reference.
105 //@ Because there cannot be another reference to the same data, we could also call it a *unique* reference, but that is not their official name.
106
107 //@ As an example, consider a function which increments every element of a vector by 1.
108 //@ The type `&mut Vec<i32>` is the type of mutable references to `vec<i32>`. Because the reference
109 //@ is mutable, we can use a mutable iterator, providing mutable references to the elements.
110 fn vec_inc(v: &mut Vec<i32>) {
111     for e in v.iter_mut() {
112         *e += 1;
113     }
114 }
115 // Here's an example of calling `vec_inc`.
116 fn mutable_ref_demo() {
117     let mut v = vec![5,4,3,2,1];
118     /* let first = &v[0]; */
119     vec_inc(&mut v);
120     vec_inc(&mut v);
121     /* println!("The first element is: {}", *first); */             /* BAD! */
122 }
123 //@ `&mut` is the operator to create a mutable reference. We have to mark `v` as mutable in order
124 //@ to create such a reference: Even though we completely own `v`, Rust tries to protect us from
125 //@ accidentally mutating things.
126 //@ Hence owned variables that you intend to mutate have to be annotated with `mut`.
127 //@ Because the reference passed to `vec_inc` only lasts as long as the function call, we can still
128 //@ call `vec_inc` on the same vector twice: The durations of the two references do not overlap, so
129 //@ we never have more than one mutable reference - we only ever borrow `v` once at a time.
130 //@ However, we can *not* create a shared reference that spans a call to `vec_inc`. Just try
131 //@ enabling the commented-out lines, and watch Rust complain. This is because `vec_inc` could mutate
132 //@ the vector structurally (i.e., it could add or remove elements), and hence the reference `first`
133 //@ could become invalid. In other words, Rust keeps us safe from bugs like the one in the C++
134 //@ snippet above.
135 //@ 
136 //@ Above, I said that having a mutable reference excludes aliasing. But if you look at the code
137 //@ above carefully, you may say: "Wait! Don't the `v` in `mutable_ref_demo` and the `v` in
138 //@ `vec_inc` alias?" And you are right, they do. However, the `v` in `mutable_ref_demo` is not
139 //@ actually usable, it is not *active*: As long as `v` is borrowed, Rust will not allow you to do
140 //@ anything with it.
141
142 // ## Summary
143 // The ownership and borrowing system of Rust enforces the following three rules:
144 // 
145 // * There is always exactly one owner of a piece of data
146 // * If there is an active mutable reference, then nobody else can have active access to the data
147 // * If there is an active shared reference, then every other active access to the data is also a
148 //   shared reference
149 // 
150 // As it turns out, combined with the abstraction facilities of Rust, this is a very powerful
151 // mechanism to tackle many problems beyond basic memory safety. You will see some examples for
152 // this soon.
153
154 //@ [index](main.html) | [previous](part03.html) | [raw source](workspace/src/part04.rs) |
155 //@ [next](part05.html)