Sub topic 8
Borrowing with Mutable References
This chapter assumes you know basic Rust syntax, can run programs with cargo, and have read the chapters on moves and shared references (&T). It covers &mut T: how to create one, what it allows, and which compiler errors you will meet.
Why mutable references exist
Passing a value by shared reference lets a function read it. Passing by ownership lets a function do anything, but you lose the value unless it is returned. A mutable reference sits between the two. The function can change the value, and the caller keeps ownership.
fn add_suffix(s: &mut String) {
s.push_str(", world");
}
fn main() {
let mut s = String::from("hello");
add_suffix(&mut s);
println!("{s}");
}This prints hello, world. Three pieces must line up:
- The variable is declared
let mut s. - The caller writes
&mut s. - The parameter type is
&mut String.
If you drop mut from the declaration, the compiler rejects &mut s with "cannot borrow s as mutable, as it is not declared as mutable". The mut keyword on the owner is the permission. The &mut at the call site is the visible marker that the callee may change your data.
Reading and writing through the reference
A &mut T points at a value of type T. To replace the whole value, dereference with *.
fn bump(n: &mut i32) {
*n += 1;
}
fn main() {
let mut x = 1;
bump(&mut x);
bump(&mut x);
println!("{x}");
}This prints 3. Method calls such as push_str do not need *, because Rust automatically dereferences the receiver. Arithmetic and assignment on the value itself do need it.
Writing *r = value drops the old value and stores the new one. This is how you replace a String or a Vec behind a reference.
Exclusive access
A &mut T is exclusive. While it is live, no other reference to the same value may be used, whether shared or mutable. The next chapter states the full borrowing rules. For now, note what the exclusivity buys you.
fn main() {
let mut s = String::from("a");
let r1 = &mut s;
// let r2 = &mut s; // error[E0499]: cannot borrow `s` as mutable more than once
r1.push('b');
println!("{r1}");
}If the commented line were active, r1 would still be used afterwards. Two live mutable references could then change the same String at once. One could trigger a reallocation while the other still points at the old buffer. Rust refuses this at compile time, so there are no data races and no invalidated pointers in safe code.
The exclusive reference also means the owner cannot be touched while the borrow is live. Reading s directly between creating r1 and using it again is an error, because reading is itself a shared borrow.
A borrow lasts until its last use
A borrow does not last until the end of the block. It lasts until the last place the reference is used. The compiler calls this non-lexical lifetimes.
fn main() {
let mut s = String::from("a");
let r1 = &mut s;
r1.push('b');
let r2 = &mut s;
r2.push('c');
println!("{s}");
}This compiles and prints abc. r1 is never used after r2 is created, so the two borrows do not overlap. The same reasoning lets you read s at the end: r2 is finished by then.
Reborrowing
When you pass a &mut T variable to a function, you might expect it to be moved, since &mut T is not Copy. In practice the compiler creates a temporary reborrow, and your original reference works again afterwards.
fn shout(s: &mut String) {
s.push('!');
}
fn main() {
let mut text = String::from("hi");
let r = &mut text;
shout(r);
shout(r);
r.push('?');
println!("{r}");
println!("{text}");
}This prints hi!!? twice. Each call to shout(r) reborrows *r for the length of the call. You can also write shout(&mut *r) to reborrow explicitly. Reborrowing is why helper functions can take &mut without consuming the caller's reference.
Mutating collections safely
The most common borrow error with mutable data is changing a collection while iterating over it.
fn main() {
let mut v = vec![1, 2, 3];
// for n in &v { v.push(*n); } // error[E0502]: cannot borrow `v` as mutable
// // because it is also borrowed as immutable
for n in v.iter_mut() {
*n *= 2;
}
println!("{:?}", v);
}This prints [2, 4, 6]. The iterator holds a borrow of v for the whole loop. Pushing would require a second, conflicting borrow, and growing the vector could move its buffer under the iterator. iter_mut hands out one &mut i32 per element instead. To add elements, collect them into a separate vector first, then extend v after the loop.
Borrowing parts of a value
The compiler tracks borrows of struct fields separately, so you can hold mutable references to different fields at once.
struct Pair {
a: String,
b: String,
}
fn main() {
let mut p = Pair { a: String::from("x"), b: String::from("y") };
let ra = &mut p.a;
let rb = &mut p.b;
ra.push('1');
rb.push('2');
println!("{} {}", p.a, p.b);
}This prints x1 y2. The compiler cannot make the same inference across a method call or an index, because &mut v[0] and &mut v[1] both borrow all of v. For slices, use split_at_mut, which returns two non-overlapping &mut slices.
Moving out of a mutable reference
A &mut T lets you change a value, but not leave it empty. This function does not compile:
// fn take_name(slot: &mut String) -> String {
// *slot // error[E0507]: cannot move out of `*slot` which is behind a mutable reference
// }The caller still owns the String, so it must hold a valid value afterwards. Replace the value instead of moving it:
use std::mem;
fn take_name(slot: &mut String) -> String {
mem::take(slot)
}
fn main() {
let mut name = String::from("Ada");
let old = take_name(&mut name);
println!("{old:?} {name:?}");
}This prints "Ada" "". mem::take swaps in Default::default(). mem::replace swaps in a value you choose, and mem::swap exchanges two places.
Shared versus mutable references
| Property | `&T` | `&mut T` |
|---|---|---|
| Can read | Yes | Yes |
| Can modify | No | Yes |
| Copyable | Yes | No, it is reborrowed |
| Simultaneous references | Many | Exactly one |
| Owner needs `mut` | No | Yes |
Common mistakes
- Forgetting
muton the variable, then adding&mutat the call site. - Writing
n += 1instead of*n += 1whennis&mut i32. - Holding
let first = &mut v[0];, callingv.push(..), then usingfirst. - Returning a
&mutto a local variable. The next chapters on dangling references and lifetimes explain why this fails.
Exercise
This code fails to compile. Which line causes the error, and how do you fix it without cloning? let mut s = String::from("hi"); let r = &mut s; println!("{s}"); r.push('!');
Show answer
The println!("{s}") line reads s while the mutable borrow r is still live, because r is used on the next line. Move the println! after r.push('!'), or print through r. Once r is no longer used, s is accessible again.
Exercise
What does this program print? fn doubleall(v: &mut Vec<i32>) { for n in v.itermut() { n = 2; } } fn main() { let mut data = vec![1, 2, 3]; doubleall(&mut data); doubleall(&mut data); println!("{:?}", data); }
Show answer
It prints [4, 8, 12]. Each call borrows data mutably for the duration of the call only, and doubles every element, so the values are multiplied by 4 overall.