Sub topic 3
Changing Borrowed Data with &mut
This chapter assumes you know basic Rust syntax, how String and Vec work, the difference between stack and heap memory, and how to build a program with cargo. It also assumes you have read the previous chapter on shared references (&T). Here you will learn how to lend a value out so the borrower can change it, and what restrictions Rust adds when you do.
Why a second kind of reference
A shared reference (&T) gives read-only access. Sometimes a function must modify the caller's data. You could take ownership and return the value, but that is clumsy for a simple edit. A mutable reference (&mut T) lets a function change a value in place while the caller keeps ownership.
fn add_suffix(s: &mut String) {
s.push_str("!");
}
fn main() {
let mut s = String::from("hi");
add_suffix(&mut s);
println!("{s}");
}This prints hi!. Three things make it work:
- The variable is declared
let mut s. You cannot take a mutable reference to a variable that is not itself mutable. - The caller writes
&mut sto create the reference. Themutat the call site makes it visible that the callee may change the value. - The parameter type is
&mut String, which tells the compiler the function needs write access.
After add_suffix returns, the mutable borrow ends. main still owns s and can print it.
Reading and writing through the reference
Inside the function, s is a reference, not the String itself. Method calls like s.push_str("!") work because Rust automatically dereferences when you call a method. For assignment you must dereference explicitly with *.
fn reset(n: &mut i32) {
*n = 0;
}
fn double(n: &mut i32) {
*n *= 2;
}
fn main() {
let mut x = 21;
double(&mut x);
println!("{x}");
reset(&mut x);
println!("{x}");
}The output is 42 and then 0. Writing n = 0 would be a type error, because n has type &mut i32 and 0 is an i32. The * operator reaches through the reference to the value it points to.
The same applies when you replace a whole String or Vec rather than calling a method on it:
fn replace_text(s: &mut String) {
*s = String::from("replaced");
}
fn main() {
let mut s = String::from("original");
replace_text(&mut s);
println!("{s}");
}The assignment drops the old String (freeing its heap buffer) and stores the new one in the same location. The caller's variable now holds the new value.
The core restriction: one mutable reference at a time
A mutable reference is exclusive. While it exists, no other reference to the same value may be used, whether shared or mutable. This is the "one writer" half of the rule covered fully in the next chapter. Here is the mutable-versus-mutable case:
fn main() {
let mut s = String::from("data");
let a = &mut s;
let b = &mut s;
a.push('1');
b.push('2');
println!("{s}");
}This does not compile. The compiler reports E0499: cannot borrow s as mutable more than once at a time. The first borrow a is still needed on the line a.push('1'), which comes after b is created, so the two borrows overlap.
The exclusivity rule exists because two live writers to the same memory is how data races and iterator invalidation happen. If a and b could both write, one could reallocate the string's buffer while the other held a pointer into it. Rust forbids this at compile time, with no cost at run time.
The rule also applies across threads, which is why safe Rust cannot produce a data race. A data race needs two threads accessing the same memory, at least one writing, with no synchronization. Exclusive &mut rules out the "two accesses, one writing" combination.
Mutable and shared references conflict
A mutable borrow also conflicts with any shared borrow that is still in use. This is the situation from the earlier ownership discussion, shown with a Vec:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}This does not compile, and the error is E0502: cannot borrow v as mutable because it is also borrowed as immutable. v.push(4) needs a mutable borrow of v. The shared borrow first is used later, in println!, so it is still alive at the point of the push.
This is more than a style rule. push may need to grow the vector. Growing allocates a new buffer, copies the elements, and frees the old buffer. After that, first would point to freed memory. In C++ the equivalent code compiles and has undefined behavior. In Rust the compiler stops you.
Fixing the conflict
The fix is to make the borrows not overlap. There are three common approaches.
Finish using the shared reference before mutating:
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
println!("{first}");
v.push(4);
println!("{:?}", v);
}Copy the value out instead of keeping a reference. For i32, which is Copy, dereferencing produces an independent value:
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0];
v.push(4);
println!("{first} {:?}", v);
}Or clone, when the element type is not Copy and you need to keep it. Cloning allocates, so use it when the cost is acceptable.
Scopes limit a mutable borrow
You can hold several mutable references to the same value over time, as long as they do not overlap. A new scope is one way to end a borrow early:
fn main() {
let mut s = String::from("x");
{
let a = &mut s;
a.push('y');
}
let b = &mut s;
b.push('z');
println!("{s}");
}This prints xyz. The braces are not required in modern Rust, because the compiler ends a borrow after its last use. The next chapters on non-lexical lifetimes explain that behavior. The scope form still works and can make intent clearer.
Cannot use the owner while it is mutably borrowed
The exclusivity applies to the owner too. While a &mut is live, you cannot read the original variable directly:
fn main() {
let mut s = String::from("hello");
let m = &mut s;
println!("{s}");
m.push('!');
}This does not compile (E0502). The println! takes a shared borrow of s while m is still needed on the next line. Swapping the last two lines fixes it, because m is then finished before s is read.
Mutable references and moves
A &mut T is not Copy. Passing it by value would normally move it, which would make the reference unusable afterwards. In practice Rust inserts an implicit reborrow when you pass a &mut to a function that expects a &mut, so you can call several functions in a row:
fn push_one(v: &mut Vec<i32>) {
v.push(1);
}
fn main() {
let mut v = Vec::new();
let r = &mut v;
push_one(r);
push_one(r);
println!("{:?}", r);
}This prints [1, 1]. The mechanism, called reborrowing, gets its own chapter later. For now, remember that passing a &mut along to a function does not usually consume it.
Common patterns
Functions that modify their argument in place often return nothing. Functions that also report a result return a value alongside the mutation:
fn drain_evens(v: &mut Vec<i32>) -> usize {
let before = v.len();
v.retain(|n| n % 2 != 0);
before - v.len()
}
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6];
let removed = drain_evens(&mut v);
println!("removed {removed}, left {:?}", v);
}The output is removed 3, left [1, 3, 5]. The function reads v.len() and mutates v in sequence. Each use of the reference is short, so there is no overlap.
Another pattern is std::mem::swap, which exchanges the contents of two mutable references. It needs two distinct &mut values, so they must point to different variables:
fn main() {
let mut a = String::from("left");
let mut b = String::from("right");
std::mem::swap(&mut a, &mut b);
println!("{a} {b}");
}This prints right left. Calling swap(&mut a, &mut a) would be rejected with E0499, since both arguments borrow a mutably.
Summary of decisions
| Situation | Use |
|---|---|
| Function only reads the value | `&T` |
| Function must change the caller's value in place | `&mut T` |
| Function consumes the value and the caller no longer needs it | `T` (move) |
| Need to read and write while other code also reads | Restructure, or interior mutability (later chapter) |
Exercise
The code below fails to compile. Name the error code, say why it fails, and give a fix that keeps the output the same. fn main() { let mut names = vec![String::from("a"), String::from("b")]; let first = &names[0]; names.push(String::from("c")); println!("{first} {}", names.len()); }
Show answer
The error is E0502. The shared borrow first is used in println! after names.push, which needs a mutable borrow, so the borrows overlap. Because push may reallocate the buffer, first could dangle. One fix is to clone the element, let first = names[0].clone();, so no borrow of names remains. Another is to compute names.len() and push after printing first, but that changes the output order, so cloning is the fix that keeps the output identical.
Exercise
Write a function fn append_all(dst: &mut Vec<i32>, src: &[i32]) that appends every element of src to dst. Then explain why calling append_all(&mut v, &v) on the same vector is rejected.
Show answer
Body: dst.extend_from_slice(src);. The call append_all(&mut v, &v) creates a mutable borrow and a shared borrow of v that are both live during the call, which is error E0502. The function could otherwise reallocate dst while reading from src, which would leave src dangling. To append a vector to itself, clone first: let copy = v.clone(); append_all(&mut v, ©);.