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