1 // Rust-101, Part 04: Ownership, Borrowing
2 // =======================================
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.
10 void foo(std::vector<int> v) {
13 *first = 1337; // This is bad!
16 // What's going wrong here? `first` is a pointer into the vector `v`. The operation `push_back`
17 // may re-allocate the storage for the vector, in case the old buffer was full. If that happens,
18 // `first` is now a dangling pointer, and accessing it can crash the program (or worse).
20 // It turns out that only the combination of two circumstances can lead to such a bug:
21 // *aliasing* and *mutation*. In the code above, we have `first` and the buffer of `v`
22 // being aliases, and when `push_back` is called, the latter is used to perform a mutation.
23 // Therefore, the central principle of the Rust typesystem is to *rule out mutation in the presence
24 // of aliasing*. The core tool to achieve that is the notion of *ownership*.
27 // What does that mean in practice? Consider the following example.
28 fn work_on_vector(v: Vec<i32>) { /* do something */ }
30 let v = vec![1,2,3,4];
32 /* println!("The first element is: {}", v[0]); */
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.
40 // If you give a book to your friend, you cannot just 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
48 // ## Shared borrowing
49 // If you go back to our example with `vec_min`, and try to call that function twice, you will
50 // get the same error. That's because `vec_min` demands that the caller transfers ownership of the
51 // vector. Hence, when `vec_min` finishes, the entire vector is deleted. That's of course not what
52 // we wanted! Can't we somehow give `vec_min` access to the vector, while retaining ownership of it?
54 // Rust calls this *borrowing* the vector, and it works a bit like borrowing does in the real world:
55 // If you borrow a book to your friend, your friend can have it and work on it (and you can't!)
56 // as long as the book is still borrowed. Your friend could even borrow the book to someone else.
57 // Eventually however, your friend has to give the book back to you, at which point you again
60 // Rust distinguishes between two kinds of borrows. First of all, there's the *shared* borrow.
61 // This is where the book metaphor kind of breaks down... you can give a shared borrow of
62 // *the same data* to lots of different people, who can all access the data. This of course
63 // introduces aliasing, so in order to live up to its promise of safety, Rust does not allow
64 // mutation through a shared borrow.
66 // So, let's re-write `vec_min` to work on a shared borrow of a vector, written `&Vec<i32>`.
67 // I also took the liberty to convert the function from `SomethingOrNothing` to the standard
68 // library type `Option`.
69 fn vec_min(v: &Vec<i32>) -> Option<i32> {
72 // In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
73 min = Some(match min {
75 Some(n) => cmp::min(n, *e)
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];
87 println!("The first element is: {}", *first);
89 // What's going on here? First, `&` is how you create a shared borrow to something. All borrows are created like
90 // this - there is no way to have something like a NULL pointer. This code creates three shared borrows to `v`:
91 // The borrow for `first` begins in the 2nd line of the function and lasts all the way to the end. The other two
92 // borrows, created for calling `vec_min`, only last for the duration of that respective call.
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.
98 // ## Mutable borrowing
99 // There is a second kind of borrow, a *mutable borrow*. As the name suggests, such a borrow permits
100 // mutation, and hence has to prevent aliasing. There can only ever be one mutable borrow to a
101 // particular piece of data.
103 // As an example, consider a function which increments every element of a vector by 1.
104 // The type `&mut Vec<i32>` is the type of mutable borrows of `vec<i32>`. Because the borrow is
105 // mutable, we can change `e` in the loop.
106 fn vec_inc(v: &mut Vec<i32>) {
111 // Here's an example of calling `vec_inc`.
112 fn mutable_borrow_demo() {
113 let mut v = vec![5,4,3,2,1];
114 /* let first = &v[0]; */
117 /* println!("The first element is: {}", *first); */
119 // `&mut` is the operator to create a mutable borrow. We have to mark `v` as mutable in order to create such a
120 // borrow. Because the borrow passed to `vec_inc` only lasts as long as the function call, we can still call
121 // `vec_inc` on the same vector twice: The durations of the two borrows do not overlap, so we never have more
122 // than one mutable borrow. However, we can *not* create a shared borrow that spans a call to `vec_inc`. Just try
123 // enabling the commented-out lines, and watch Rust complain. This is because `vec_inc` could mutate
124 // the vector structurally (i.e., it could add or remove elements), and hence the pointer `first`
125 // could become invalid. In other words, Rust keeps us safe from bugs like the one in the C++ snipped above.
127 // Above, I said that having a mutable borrow excludes aliasing. But if you look at the code above carefully,
128 // you may say: "Wait! Don't the `v` in `mutable_borrow_demo` and the `v` in `vec_inc` alias?" And you are right,
129 // they do. However, the `v` in `mutable_borrow_demo` is not actually usable, it is not *active*: As long as there is an
130 // outstanding borrow, Rust will not allow you to do anything with `v`.
133 // The ownership and borrowing system of Rust enforces the following three rules:
135 // * There is always exactly one owner of a piece of data
136 // * If there is an active mutable borrow, then nobody else can have active access to the data
137 // * If there is an active shared borrow, then every other active access to the data is also a shared borrow
139 // As it turns out, combined with the abstraction facilities of Rust, this is a very powerful mechanism
140 // to tackle many problems beyond basic memory safety. You will see some examples for this soon.
142 // [index](main.html) | [previous](part03.html) | [next](part05.html)