remove workspace from the repository, instead generate a zipfile to upload
[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 ownership
41 //@ has been transferred somewhere else. In this particular case, the buffer storing the data
42 //@ 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* the vector, and it considers references as *borrowing* ownership. This
53 //@ works a bit like borrowing does in the real world: If your friend borrows a book from you, your friend
54 //@ can have it and work on it (and you can't!) as long as the book is still borrowed. Your friend could
55 //@ even lend the book to someone else. Eventually however, your friend has to give the book back to you,
56 //@ 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 allow
62 //@ 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 borrows the vector
72     // 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 shared reference.
92 //@ `shared_ref_demo` creates three shared references to `v`:
93 //@ The reference `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*. This is a reference that comes with the promise
102 //@ that nobody else has *any kind of access* to the referee - in contrast to shared references, there is no aliasing with mutable references. It is thus always safe to perform mutation through such a reference.
103 //@ 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.
104
105 //@ As an example, consider a function which increments every element of a vector by 1.
106 //@ The type `&mut Vec<i32>` is the type of mutable references to `vec<i32>`. Because the reference is
107 //@ mutable, we can use a mutable iterator, providing mutable references to the elements.
108 fn vec_inc(v: &mut Vec<i32>) {
109     for e in v.iter_mut() {
110         *e += 1;
111     }
112 }
113 // Here's an example of calling `vec_inc`.
114 fn mutable_ref_demo() {
115     let mut v = vec![5,4,3,2,1];
116     /* let first = &v[0]; */
117     vec_inc(&mut v);
118     vec_inc(&mut v);
119     /* println!("The first element is: {}", *first); */             /* BAD! */
120 }
121 //@ `&mut` is the operator to create a mutable reference. We have to mark `v` as mutable in order to create such a
122 //@ reference: Even though we completely own `v`, Rust tries to protect us from accidentally mutating things.
123 //@ Hence owned variables that you intend to mutate have to be annotated with `mut`.
124 //@ Because the reference passed to `vec_inc` only lasts as long as the function call, we can still call
125 //@ `vec_inc` on the same vector twice: The durations of the two references do not overlap, so we never have more
126 //@ than one mutable reference - we only ever borrow `v` once at a time. However, we can *not* create a shared reference that spans a call to `vec_inc`. Just try
127 //@ enabling the commented-out lines, and watch Rust complain. This is because `vec_inc` could mutate
128 //@ the vector structurally (i.e., it could add or remove elements), and hence the reference `first`
129 //@ could become invalid. In other words, Rust keeps us safe from bugs like the one in the C++ snippet above.
130 //@ 
131 //@ Above, I said that having a mutable reference excludes aliasing. But if you look at the code above carefully,
132 //@ you may say: "Wait! Don't the `v` in `mutable_ref_demo` and the `v` in `vec_inc` alias?" And you are right,
133 //@ they do. However, the `v` in `mutable_ref_demo` is not actually usable, it is not *active*: As long as `v` is
134 //@ borrowed, Rust will not allow you to do anything with it.
135
136 // ## Summary
137 // The ownership and borrowing system of Rust enforces the following three rules:
138 // 
139 // * There is always exactly one owner of a piece of data
140 // * If there is an active mutable reference, then nobody else can have active access to the data
141 // * If there is an active shared reference, then every other active access to the data is also a shared reference
142 // 
143 // As it turns out, combined with the abstraction facilities of Rust, this is a very powerful mechanism
144 // to tackle many problems beyond basic memory safety. You will see some examples for this soon.
145
146 //@ [index](main.html) | [previous](part03.html) | [raw source](workspace/src/part04.rs) | [next](part05.html)