1 % References and Borrowing
3 This is the second of three sections presenting Rust’s ownership system. This is one of
4 Rust’s most distinct and compelling features, with which Rust developers should
5 become quite acquainted. Ownership is how Rust achieves its largest goal,
6 memory safety. There are a few distinct concepts, each with its own
9 * [ownership][ownership], the key concept
10 * borrowing, which you’re reading now
11 * [lifetimes][lifetimes], an advanced concept of borrowing
13 These three chapters are related, and in order. You’ll need all three to fully
14 understand the ownership system.
16 [ownership]: ownership.html
17 [lifetimes]: lifetimes.html
21 Before we get to the details, two important notes about the ownership system.
23 Rust has a focus on safety and speed. It accomplishes these goals through many
24 ‘zero-cost abstractions’, which means that in Rust, abstractions cost as little
25 as possible in order to make them work. The ownership system is a prime example
26 of a zero-cost abstraction. All of the analysis we’ll talk about in this guide
27 is _done at compile time_. You do not pay any run-time cost for any of these
30 However, this system does have a certain cost: learning curve. Many new users
31 to Rust experience something we like to call ‘fighting with the borrow
32 checker’, where the Rust compiler refuses to compile a program that the author
33 thinks is valid. This often happens because the programmer’s mental model of
34 how ownership should work doesn’t match the actual rules that Rust implements.
35 You probably will experience similar things at first. There is good news,
36 however: more experienced Rust developers report that once they work with the
37 rules of the ownership system for a period of time, they fight the borrow
38 checker less and less.
40 With that in mind, let’s learn about borrowing.
44 At the end of the [ownership][ownership] section, we had a nasty function that looked
48 fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {
49 // do stuff with v1 and v2
51 // hand back ownership, and the result of our function
55 let v1 = vec![1, 2, 3];
56 let v2 = vec![1, 2, 3];
58 let (v1, v2, answer) = foo(v1, v2);
61 This is not idiomatic Rust, however, as it doesn’t take advantage of borrowing. Here’s
65 fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
66 // do stuff with v1 and v2
72 let v1 = vec![1, 2, 3];
73 let v2 = vec![1, 2, 3];
75 let answer = foo(&v1, &v2);
77 // we can use v1 and v2 here!
80 A more concrete example:
84 // Don't worry if you don't understand how `fold` works, the point here is that an immutable reference is borrowed.
85 fn sum_vec(v: &Vec<i32>) -> i32 {
86 return v.iter().fold(0, |a, &b| a + b);
88 // Borrow two vectors and sum them.
89 // This kind of borrowing does not allow mutation through the borrowed reference.
90 fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
91 // do stuff with v1 and v2
98 let v1 = vec![1, 2, 3];
99 let v2 = vec![4, 5, 6];
101 let answer = foo(&v1, &v2);
102 println!("{}", answer);
106 Instead of taking `Vec<i32>`s as our arguments, we take a reference:
107 `&Vec<i32>`. And instead of passing `v1` and `v2` directly, we pass `&v1` and
108 `&v2`. We call the `&T` type a ‘reference’, and rather than owning the resource,
109 it borrows ownership. A binding that borrows something does not deallocate the
110 resource when it goes out of scope. This means that after the call to `foo()`,
111 we can use our original bindings again.
113 References are immutable, like bindings. This means that inside of `foo()`,
114 the vectors can’t be changed at all:
117 fn foo(v: &Vec<i32>) {
126 will give us this error:
129 error: cannot borrow immutable borrowed content `*v` as mutable
134 Pushing a value mutates the vector, and so we aren’t allowed to do it.
138 There’s a second kind of reference: `&mut T`. A ‘mutable reference’ allows you
139 to mutate the resource you’re borrowing. For example:
150 This will print `6`. We make `y` a mutable reference to `x`, then add one to
151 the thing `y` points at. You’ll notice that `x` had to be marked `mut` as well.
152 If it wasn’t, we couldn’t take a mutable borrow to an immutable value.
154 You'll also notice we added an asterisk (`*`) in front of `y`, making it `*y`,
155 this is because `y` is a `&mut` reference. You'll need to use asterisks to
156 access the contents of a reference as well.
158 Otherwise, `&mut` references are like references. There _is_ a large
159 difference between the two, and how they interact, though. You can tell
160 something is fishy in the above example, because we need that extra scope, with
161 the `{` and `}`. If we remove them, we get an error:
164 error: cannot borrow `x` as immutable because it is also borrowed as mutable
167 note: previous borrow of `x` occurs here; the mutable borrow prevents
168 subsequent moves, borrows, or modification of `x` until the borrow ends
171 note: previous borrow ends here
178 As it turns out, there are rules.
182 Here are the rules for borrowing in Rust:
184 First, any borrow must last for a scope no greater than that of the owner.
185 Second, you may have one or the other of these two kinds of borrows, but not
186 both at the same time:
188 * one or more references (`&T`) to a resource,
189 * exactly one mutable reference (`&mut T`).
192 You may notice that this is very similar to, though not exactly the same as,
193 the definition of a data race:
195 > There is a ‘data race’ when two or more pointers access the same memory
196 > location at the same time, where at least one of them is writing, and the
197 > operations are not synchronized.
199 With references, you may have as many as you’d like, since none of them are
200 writing. However, as we can only have one `&mut` at a time, it is impossible to
201 have a data race. This is how Rust prevents data races at compile time: we’ll
202 get errors if we break the rules.
204 With this in mind, let’s consider our example again.
206 ## Thinking in scopes
221 This code gives us this error:
224 error: cannot borrow `x` as immutable because it is also borrowed as mutable
229 This is because we’ve violated the rules: we have a `&mut T` pointing to `x`,
230 and so we aren’t allowed to create any `&T`s. It's one or the other. The note
231 hints at how to think about this problem:
234 note: previous borrow ends here
241 In other words, the mutable borrow is held through the rest of our example. What
242 we want is for the mutable borrow by `y` to end so that the resource can be
243 returned to the owner, `x`. `x` can then provide an immutable borrow to `println!`.
244 In Rust, borrowing is tied to the scope that the borrow is valid for. And our
245 scopes look like this:
251 let y = &mut x; // -+ &mut borrow of x starts here
255 println!("{}", x); // -+ - try to borrow x here
256 } // -+ &mut borrow of x ends here
260 The scopes conflict: we can’t make an `&x` while `y` is in scope.
262 So when we add the curly braces:
268 let y = &mut x; // -+ &mut borrow starts here
270 } // -+ ... and ends here
272 println!("{}", x); // <- try to borrow x here
275 There’s no problem. Our mutable borrow goes out of scope before we create an
276 immutable one. So scope is the key to seeing how long a borrow lasts for.
278 ## Issues borrowing prevents
280 Why have these restrictive rules? Well, as we noted, these rules prevent data
281 races. What kinds of issues do data races cause? Here are a few.
283 ### Iterator invalidation
285 One example is ‘iterator invalidation’, which happens when you try to mutate a
286 collection that you’re iterating over. Rust’s borrow checker prevents this from
290 let mut v = vec![1, 2, 3];
297 This prints out one through three. As we iterate through the vector, we’re
298 only given references to the elements. And `v` is itself borrowed as immutable,
299 which means we can’t change it while we’re iterating:
302 let mut v = vec![1, 2, 3];
313 error: cannot borrow `v` as mutable because it is also borrowed as immutable
316 note: previous borrow of `v` occurs here; the immutable borrow prevents
317 subsequent moves or mutable borrows of `v` until the borrow ends
320 note: previous borrow ends here
328 We can’t modify `v` because it’s borrowed by the loop.
332 References must not live longer than the resource they refer to. Rust will
333 check the scopes of your references to ensure that this is true.
335 If Rust didn’t check this property, we could accidentally use a reference
336 which was invalid. For example:
351 error: `x` does not live long enough
354 note: reference must be valid for the block suffix following statement 0 at
362 note: ...but borrowed value is only valid for the block suffix following
369 In other words, `y` is only valid for the scope where `x` exists. As soon as
370 `x` goes away, it becomes invalid to refer to it. As such, the error says that
371 the borrow ‘doesn’t live long enough’ because it’s not valid for the right
374 The same problem occurs when the reference is declared _before_ the variable it
375 refers to. This is because resources within the same scope are freed in the
376 opposite order they were declared:
389 error: `x` does not live long enough
392 note: reference must be valid for the block suffix following statement 0 at
401 note: ...but borrowed value is only valid for the block suffix following
410 In the above example, `y` is declared before `x`, meaning that `y` lives longer
411 than `x`, which is not allowed.