add links to raw source
[rust-101.git] / src / part04.rs
1 // Rust-101, Part 04: Ownership, Borrowing
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 // ## Shared borrowing
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 *borrowing* the vector, and it works a bit like borrowing does in the real world:
53 //@ If you borrow a book to your friend, your friend can have it and work on it (and you can't!)
54 //@ as long as the book is still borrowed. Your friend could even borrow the book to someone else.
55 //@ Eventually however, your friend has to give the book back to you, at which point you again
56 //@ have full control.
57 //@ 
58 //@ Rust distinguishes between two kinds of borrows. First of all, there's the *shared* borrow.
59 //@ This is where the book metaphor kind of breaks down... you can give a shared borrow of
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 does not allow
62 //@ mutation through a shared borrow.
63
64 //@ So, let's re-write `vec_min` to work on a shared borrow of 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` borrows the vector
72     // it works on, and provides shared borrows of 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_borrow_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 create a shared borrow to something. All borrows are created like
92 //@ this - there is no way to have something like a  NULL pointer. This code creates three shared borrows to `v`:
93 //@ The borrow for `first` begins in the 2nd line of the function and lasts all the way to the end. The other two
94 //@ borrows, created for calling `vec_min`, only last for the duration of that respective call.
95 //@ 
96 //@ Technically, of course, borrows are pointers. Notice that since `vec_min` only gets a shared
97 //@ borrow, Rust knows that it cannot mutate `v` in any way. Hence the pointer into the buffer of `v`
98 //@ that was created before calling `vec_min` remains valid.
99
100 // ## Mutable borrowing
101 //@ There is a second kind of borrow, a *mutable borrow*. As the name suggests, such a borrow permits
102 //@ mutation, and hence has to prevent aliasing. There can only ever be one mutable borrow to a
103 //@ particular piece of data.
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 borrows of `vec<i32>`. Because the borrow is
107 //@ mutable, we can use a mutable iterator, providing a mutable borrow of 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_borrow_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 borrow. We have to mark `v` as mutable in order to create such a
122 //@ borrow: 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 borrow 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 borrows do not overlap, so we never have more
126 //@ than one mutable borrow. However, we can *not* create a shared borrow 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 pointer `first`
129 //@ could become invalid. In other words, Rust keeps us safe from bugs like the one in the C++ snipped above.
130 //@ 
131 //@ Above, I said that having a mutable borrow excludes aliasing. But if you look at the code above carefully,
132 //@ you may say: "Wait! Don't the `v` in `mutable_borrow_demo` and the `v` in `vec_inc` alias?" And you are right,
133 //@ they do. However, the `v` in `mutable_borrow_demo` is not actually usable, it is not *active*: As long as there is an
134 //@ outstanding borrow, Rust will not allow you to do anything with `v`.
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 borrow, then nobody else can have active access to the data
141 // * If there is an active shared borrow, then every other active access to the data is also a shared borrow
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](https://www.ralfj.de/git/rust-101.git/blob_plain/HEAD:/workspace/src/part04.rs) | [next](part05.html)