1 // Rust-101, Part 04: Ownership, Borrowing, References
2 // ===================================================
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.
8 void foo(std::vector<int> v) {
11 *first = 1337; // This is bad!
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).
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*.
25 //@ What does that mean in practice? Consider the following example.
26 fn work_on_vector(v: Vec<i32>) { /* do something */ }
28 let v = vec![1,2,3,4];
30 /* println!("The first element is: {}", v[0]); */ /* BAD! */
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.
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
41 //@ ownership has been transferred somewhere else. In this particular case, the buffer storing the
42 //@ data 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
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?
52 //@ Rust calls this *a reference* to the vector, and it considers references as *borrowing*
53 //@ ownership. This works a bit like borrowing does in the real world: If your friend borrows a
54 //@ book from you, your friend can have it and work on it (and you can't!) as long as the book is
55 //@ still borrowed. Your friend could even lend the book to someone else. Eventually however, your
56 //@ friend has to give the book back to you, at which point you again have full control.
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
62 //@ allow mutation through a shared reference.
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> {
71 // This time, we explicitly request an iterator for the vector `v`. The method `iter` just
72 // borrows the vector it works on, and provides shared references to the elements.
74 // In the loop, `e` now has type `&i32`, so we have to dereference it to obtain an `i32`.
75 min = Some(match min {
77 Some(n) => cmp::min(n, *e)
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];
89 println!("The first element is: {}", *first);
91 //@ What's going on here? First, `&` is how you lend ownership to someone - this operator creates a
92 //@ shared reference. `shared_ref_demo` creates three shared references to `v`: The reference
93 //@ `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.
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.
100 // ## Unique, mutable references
102 //@ There is a second way to borrow something, a second kind of reference: The *mutable reference*.
103 //@ This is a reference that comes with the promise that nobody else has *any kind of access* to
104 //@ the referee - in contrast to shared references, there is no aliasing with mutable references.
105 //@ It is thus always safe to perform mutation through such a reference.
106 //@ 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.
108 //@ As an example, consider a function which increments every element of a vector by 1.
109 //@ The type `&mut Vec<i32>` is the type of mutable references to `vec<i32>`. Because the reference
110 //@ is mutable, we can use a mutable iterator, providing mutable references to the elements.
111 fn vec_inc(v: &mut Vec<i32>) {
112 for e in v.iter_mut() {
116 // Here's an example of calling `vec_inc`.
117 fn mutable_ref_demo() {
118 let mut v = vec![5,4,3,2,1];
119 /* let first = &v[0]; */
122 /* println!("The first element is: {}", *first); */ /* BAD! */
125 //@ `&mut` is the operator to create a mutable reference. We have to mark `v` as mutable in order
126 //@ to create such a reference: Even though we completely own `v`, Rust tries to protect us from
127 //@ accidentally mutating things.
128 //@ Hence owned variables that you intend to mutate have to be annotated with `mut`.
129 //@ Because the reference passed to `vec_inc` only lasts as long as the function call, we can still
130 //@ call `vec_inc` on the same vector twice: The durations of the two references do not overlap, so
131 //@ we never have more than one mutable reference - we only ever borrow `v` once at a time.
132 //@ However, we can *not* create a shared reference that spans a call to `vec_inc`. Just try
133 //@ enabling the commented-out lines, and watch Rust complain. This is because `vec_inc` could mutate
134 //@ the vector structurally (i.e., it could add or remove elements), and hence the reference `first`
135 //@ could become invalid. In other words, Rust keeps us safe from bugs like the one in the C++
138 //@ Above, I said that having a mutable reference excludes aliasing. But if you look at the code
139 //@ above carefully, you may say: "Wait! Don't the `v` in `mutable_ref_demo` and the `v` in
140 //@ `vec_inc` alias?" And you are right, they do. However, the `v` in `mutable_ref_demo` is not
141 //@ actually usable, it is not *active*: As long as `v` is borrowed, Rust will not allow you to do
142 //@ anything with it.
145 // The ownership and borrowing system of Rust enforces the following three rules:
147 // * There is always exactly one owner of a piece of data
148 // * If there is an active mutable reference, then nobody else can have active access to the data
149 // * If there is an active shared reference, then every other active access to the data is also a
152 // As it turns out, combined with the abstraction facilities of Rust, this is a very powerful
153 // mechanism to tackle many problems beyond basic memory safety. You will see some examples for
156 //@ [index](main.html) | [previous](part03.html) | [raw source](workspace/src/part04.rs) |
157 //@ [next](part05.html)