add part of ownership and borrowing
[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 reference 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 take(v: Vec<i32>) { /* do something */ }
29 fn foo1() {
30     let v = vec![1,2,3,4];
31     take(v);
32     /* println!("The first element is: {}", v[0]); */
33 }
34 // Rust attaches additional meaning to the argument of `take`: The function can assume
35 // that it entirely *owns* `v`, and hence can do anything with it. When `take` ends,
36 // nobody needs `v` anymore, so it will be deleted (including its buffer on the heap).
37 // Passing a `Vec<i32>` to `take` 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 some 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 `foo1`. 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. The `e` in the loop now gets type
67 // `&i32`, hence we have to deference it.
68 fn vec_min(v: &Vec<i32>) -> Option<i32> {
69     let mut min = None;
70     for e in v {
71         min = Some(match min {
72             None => *e,
73             Some(n) => cmp::min(n, *e)
74         });
75     }
76     min
77 }
78
79 // 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
80 fn foo2() {
81     let v = vec![5,4,3,2,1];
82     let first = &v[0];
83     vec_min(&v);
84     vec_min(&v);
85     println!("The first element is: {}", *first);
86 }
87 // What's going on here? First, `&` is how you create a shared borrow to something. This code creates three
88 // shared borrows to `v`: The borrow for `first` begins in the 2nd line of the function and lasts all the way to
89 // the end. The other two borrows, created for calling `vec_min`, only last for the duration of that
90 // call.
91 // 
92 // Technically, of course, borrows are pointers. Notice that since `vec_min` only gets a shared
93 // borrow, Rust knows that it cannot mutate `v` in any way. Hence the pointer created before calling
94 // `vec_min` remains valid.
95
96 // There is a second kind of borrow, a *mutable borrow*. As the name suggests, such a borrow permits
97 // mutation, and hence has to prevent aliasing. There can only ever be one mutable borrow to a
98 // particular piece of data.
99
100 // As an example, consider a function which increments every element of a vector by 1.
101 fn vec_inc(v: &mut Vec<i32>) {
102     for e in v {
103         *e += 1;
104     }
105 }
106 // The type `&mut Vec<i32>` is the type of mutable borrows of `vec<i32>`. Because the borrow is
107 // mutable, we can change `e` in the loop. How can we call this function?
108 fn foo3() {
109     let mut v = vec![5,4,3,2,1];
110     /* let first = &v[0]; */
111     vec_inc(&mut v);
112     vec_inc(&mut v);
113     /* println!("The first element is: {}", *first); */
114 }
115 // `&mut` is the operator to create a mutable borrow. We have to mark `v` as mutable in order
116 // to create such a borrow. Because the borrow passed to `vec_inc` only lasts as
117 // long as the function call, we can still call `vec_inc` on the same vector twice:
118 // The durations of the two borrows do not overlap, so we never have more than one mutable borrow.
119 // However, we can *not* create a shared borrow that spans a call to `vec_inc`. Just try
120 // enabling the commented-out lines. This is because `vec_inc` could mutate the vector structurally
121 // (i.e., it could add or remove elements), and hence the pointer `first` could become invalid.
122 // 
123 // Above, I said that having a mutable borrow excludes aliasing. But if you look at the code above carefully,
124 // you may say: "Wait! Don't the `v` in `foo3` and the `v` in `vec_inc` alias?" And you are right,
125 // they do. However, the `v` in `foo3` is not actually usable, it is not *active*: As long as there is an
126 // outstanding borrow, Rust will not allow you to do anything with `v`. This is, in fact, what
127 // prevents the creation of a mutable borrow when there already is a shared one.
128
129 // This also works the other way around: In `foo4`, there is already a mutable borrow active in the `vec_min`
130 // line, so the attempt to create another shared borrow is rejected by the compiler.
131 fn foo4() {
132     let mut v = vec![5,4,3,2,1];
133     let first = &mut v[0];
134     /* vec_min(&v); */
135     println!("The first element is: {}", *first);
136 }
137
138 // So, to summarize: The ownership and borrowing system of Rust enforces the following three rules:
139 // 
140 // * There is always exactly one owner of a piece of data
141 // * If there is an active mutable borrow, then nobody else can have active access to the data
142 // * If there is an active shared borrow, then every other active access to the data is also a shared borrow
143 // 
144 // As it turns out, combined with the abstraction facilities of Rust, this is a very powerful mechanism
145 // to tackle many problems beyond basic memory safety.
146
147 // [index](main.html) | [previous](part03.html) | [next](main.html)