Sub topic 3
Changing borrowed data with &mut
This chapter assumes you can write basic Rust functions, know the difference between String and &str, and have read the previous chapter on shared references (&T). A shared reference lets a function read a value. This chapter covers the mutable reference, which lets a function change the value without taking ownership of it.
What a mutable reference is
A mutable reference, written &mut T, is a borrow that allows writing. The owner keeps ownership. When the borrow ends, the owner can use the value again, including any changes made through the reference.
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!. The function receives the caller's String, not a copy and not ownership of it. Because s was only lent, main can still print it afterwards.
Two places you write mut
Mutability must be declared in two places, and each one means something different.
let mut ssays the variable is allowed to change. Without it, you cannot take a&mutborrow of the variable.&mut sat the call site and&mut Stringin the parameter type say this particular borrow is allowed to write.
If you leave out the first one, the compiler rejects the borrow:
fn add_suffix(s: &mut String) {
s.push_str("!");
}
fn main() {
let s = String::from("hi");
add_suffix(&mut s);
println!("{s}");
}This does not compile. The error is E0596: cannot borrow 's' as mutable, as it is not declared as mutable. The fix is to write let mut s.
Only one mutable borrow at a time
While a &mut borrow is alive, no other reference to the same value may be used. That includes a second &mut. Rust enforces this so that two parts of the program can never change the same data at once, which rules out data races and surprises such as a vector reallocating while something else points into it.
fn main() {
let mut s = String::from("a");
let r1 = &mut s;
let r2 = &mut s;
r1.push('b');
r2.push('c');
}This does not compile. The error is E0499: cannot borrow 's' as mutable more than once at a time. The compiler points at both borrows and at the later use of r1, which is what keeps the first borrow alive. The next chapter covers the full rule for mixing shared and mutable borrows.
Two mutable borrows are fine when their lifetimes do not overlap. If r1 is last used before r2 is created, the code compiles.
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 prints abc. The borrow r1 ends after its last use, so r2 starts with no conflict.
Mutating through the reference
Inside the function, s is a &mut String. Method calls such as push_str work directly because Rust follows the reference automatically. To replace the whole value, dereference with *:
fn reset(s: &mut String) {
*s = String::from("new");
}
fn main() {
let mut s = String::from("old");
reset(&mut s);
println!("{s}");
}Without the *, you would be trying to assign a String to a variable of type &mut String, which is a type error. The assignment drops the old String and stores the new one in the caller's variable.
Common errors at a glance
| Error | Message | Usual fix |
|---|---|---|
| E0596 | cannot borrow as mutable, as it is not declared as mutable | Add `mut` to the `let` binding |
| E0499 | cannot borrow as mutable more than once at a time | Finish using the first `&mut` before creating the second |
Exercise
This program fails to compile. Name the error code and give a one-line fix. let v = Vec::new(); let r = &mut v; r.push(1);
Show answer
It fails with E0596 because v is not declared mutable. Change the first statement to let mut v = Vec::new();.