1 ## References and Borrowing
3 The issue with the tuple code in Listing 4-5 is that we have to return the
4 `String` to the calling function so we can still use the `String` after the
5 call to `calculate_length`, because the `String` was moved into
8 Here is how you would define and use a `calculate_length` function that has a
9 reference to an object as a parameter instead of taking ownership of the
12 <span class="filename">Filename: src/main.rs</span>
15 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs:all}}
18 First, notice that all the tuple code in the variable declaration and the
19 function return value is gone. Second, note that we pass `&s1` into
20 `calculate_length` and, in its definition, we take `&String` rather than
23 These ampersands are *references*, and they allow you to refer to some value
24 without taking ownership of it. Figure 4-5 shows a diagram.
26 <img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" />
28 <span class="caption">Figure 4-5: A diagram of `&String s` pointing at `String
31 > Note: The opposite of referencing by using `&` is *dereferencing*, which is
32 > accomplished with the dereference operator, `*`. We’ll see some uses of the
33 > dereference operator in Chapter 8 and discuss details of dereferencing in
36 Let’s take a closer look at the function call here:
39 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-07-reference/src/main.rs:here}}
42 The `&s1` syntax lets us create a reference that *refers* to the value of `s1`
43 but does not own it. Because it does not own it, the value it points to will
44 not be dropped when the reference stops being used.
46 Likewise, the signature of the function uses `&` to indicate that the type of
47 the parameter `s` is a reference. Let’s add some explanatory annotations:
50 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-08-reference-with-annotations/src/main.rs:here}}
53 The scope in which the variable `s` is valid is the same as any function
54 parameter’s scope, but we don’t drop what the reference points to when `s`
55 stops being used because we don’t have ownership. When functions have
56 references as parameters instead of the actual values, we won’t need to return
57 the values in order to give back ownership, because we never had ownership.
59 We call the action of creating a reference *borrowing*. As in real life, if a
60 person owns something, you can borrow it from them. When you’re done, you have
63 So what happens if we try to modify something we’re borrowing? Try the code in
64 Listing 4-6. Spoiler alert: it doesn’t work!
66 <span class="filename">Filename: src/main.rs</span>
68 ```rust,ignore,does_not_compile
69 {{#rustdoc_include ../listings/ch04-understanding-ownership/listing-04-06/src/main.rs}}
72 <span class="caption">Listing 4-6: Attempting to modify a borrowed value</span>
77 {{#include ../listings/ch04-understanding-ownership/listing-04-06/output.txt}}
80 Just as variables are immutable by default, so are references. We’re not
81 allowed to modify something we have a reference to.
83 ### Mutable References
85 We can fix the error in the code from Listing 4-6 with just a few small tweaks:
87 <span class="filename">Filename: src/main.rs</span>
90 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-09-fixes-listing-04-06/src/main.rs}}
93 First, we had to change `s` to be `mut`. Then we had to create a mutable
94 reference with `&mut s` where we call the `change` function, and update the
95 function signature to accept a mutable reference with `some_string: &mut
96 String`. This makes it very clear that the `change` function will mutate the
99 But mutable references have one big restriction: you can have only one mutable
100 reference to a particular piece of data at a time. This code will fail:
102 <span class="filename">Filename: src/main.rs</span>
104 ```rust,ignore,does_not_compile
105 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/src/main.rs:here}}
111 {{#include ../listings/ch04-understanding-ownership/no-listing-10-multiple-mut-not-allowed/output.txt}}
114 This error says that this code is invalid because we cannot borrow `s` as
115 mutable more than once at a time. The first mutable borrow is in `r1` and must
116 last until it’s used in the `println!`, but between the creation of that
117 mutable reference and its usage, we tried to create another mutable reference
118 in `r2` that borrows the same data as `r1`.
120 The restriction preventing multiple mutable references to the same data at the
121 same time allows for mutation but in a very controlled fashion. It’s something
122 that new Rustaceans struggle with, because most languages let you mutate
125 The benefit of having this restriction is that Rust can prevent data races at
126 compile time. A *data race* is similar to a race condition and happens when
127 these three behaviors occur:
129 * Two or more pointers access the same data at the same time.
130 * At least one of the pointers is being used to write to the data.
131 * There’s no mechanism being used to synchronize access to the data.
133 Data races cause undefined behavior and can be difficult to diagnose and fix
134 when you’re trying to track them down at runtime; Rust prevents this problem
135 from happening because it won’t even compile code with data races!
137 As always, we can use curly brackets to create a new scope, allowing for
138 multiple mutable references, just not *simultaneous* ones:
141 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-11-muts-in-separate-scopes/src/main.rs:here}}
144 A similar rule exists for combining mutable and immutable references. This code
147 ```rust,ignore,does_not_compile
148 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/src/main.rs:here}}
154 {{#include ../listings/ch04-understanding-ownership/no-listing-12-immutable-and-mutable-not-allowed/output.txt}}
157 Whew! We *also* cannot have a mutable reference while we have an immutable one.
158 Users of an immutable reference don’t expect the values to suddenly change out
159 from under them! However, multiple immutable references are okay because no one
160 who is just reading the data has the ability to affect anyone else’s reading of
163 Note that a reference’s scope starts from where it is introduced and continues
164 through the last time that reference is used. For instance, this code will
165 compile because the last usage of the immutable references, the `println!`,
166 occurs before the mutable reference is introduced:
169 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-13-reference-scope-ends/src/main.rs:here}}
172 The scopes of the immutable references `r1` and `r2` end after the `println!`
173 where they are last used, which is before the mutable reference `r3` is
174 created. These scopes don’t overlap, so this code is allowed. The ability of
175 the compiler to tell that a reference is no longer being used at a point before
176 the end of the scope is called Non-Lexical Lifetimes (NLL for short), and you
177 can read more about it in [The Edition Guide][nll].
179 Even though borrowing errors may be frustrating at times, remember that it’s
180 the Rust compiler pointing out a potential bug early (at compile time rather
181 than at runtime) and showing you exactly where the problem is. Then you don’t
182 have to track down why your data isn’t what you thought it was.
184 ### Dangling References
186 In languages with pointers, it’s easy to erroneously create a *dangling
187 pointer*, a pointer that references a location in memory that may have been
188 given to someone else, by freeing some memory while preserving a pointer to
189 that memory. In Rust, by contrast, the compiler guarantees that references will
190 never be dangling references: if you have a reference to some data, the
191 compiler will ensure that the data will not go out of scope before the
192 reference to the data does.
194 Let’s try to create a dangling reference, which Rust will prevent with a
197 <span class="filename">Filename: src/main.rs</span>
199 ```rust,ignore,does_not_compile
200 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-14-dangling-reference/src/main.rs}}
206 {{#include ../listings/ch04-understanding-ownership/no-listing-14-dangling-reference/output.txt}}
209 This error message refers to a feature we haven’t covered yet: lifetimes. We’ll
210 discuss lifetimes in detail in Chapter 10. But, if you disregard the parts
211 about lifetimes, the message does contain the key to why this code is a problem:
214 this function's return type contains a borrowed value, but there is no value
215 for it to be borrowed from.
218 Let’s take a closer look at exactly what’s happening at each stage of our
221 <span class="filename">Filename: src/main.rs</span>
223 ```rust,ignore,does_not_compile
224 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-15-dangling-reference-annotated/src/main.rs:here}}
227 Because `s` is created inside `dangle`, when the code of `dangle` is finished,
228 `s` will be deallocated. But we tried to return a reference to it. That means
229 this reference would be pointing to an invalid `String`. That’s no good! Rust
230 won’t let us do this.
232 The solution here is to return the `String` directly:
235 {{#rustdoc_include ../listings/ch04-understanding-ownership/no-listing-16-no-dangle/src/main.rs:here}}
238 This works without any problems. Ownership is moved out, and nothing is
241 ### The Rules of References
243 Let’s recap what we’ve discussed about references:
245 * At any given time, you can have *either* one mutable reference *or* any
246 number of immutable references.
247 * References must always be valid.
249 Next, we’ll look at a different kind of reference: slices.
251 [nll]: https://doc.rust-lang.org/edition-guide/rust-2018/ownership-and-lifetimes/non-lexical-lifetimes.html