Mutable references
A & reference only lets you read a value. Back to the book: sometimes a friend asks for it not to read but to make notes in the margins. That takes a separate permission, and the book comes back to you with the notes in it.
Let's see what happens if you try to add a character to a string through an ordinary reference:
fn add_mark(s: &String) {
s.push('!'); // ✗
}
fn main() {
let name = String::from("Anna");
add_mark(&name);
println!("{name}");
}error[E0596]: cannot borrow `*s` as mutable, as it is behind a `&` referenceThe program does not build: s is a & reference, and you cannot change the string through it. The star in *s means "the string s looks at"; more on it below in this lesson. The compiler suggests a way out: make the parameter a mutable reference, &mut String.
A &mut reference
A mutable reference is a reference through which you can change the value. You create it with &mut name, and the type of a mutable reference to a String is written &mut String. Ownership does not move here either: the string stays with the calling code, only changed.
fn add_mark(s: &mut String) {
s.push('!');
}
fn main() {
let mut name = String::from("Anna");
add_mark(&mut name);
add_mark(&mut name);
println!("{name}"); // Anna!!
}Let's go through the example line by line:
- The parameter
shas the type&mut String: the function gets the right to change someone else's string. let mut namedeclares a mutable variable. Withoutmutyou cannot take a mutable reference to it.add_mark(&mut name)lends the string for writing, ands.push('!')adds the character tonameitself.- The second call adds one more
!. println!printsAnna!!: the ownernamesees both changes.
A &mut points to name itself, not to a copy of it, so it is name that changes. In the previous theme, add_mark took the string and handed it back as its result. With &mut there is nothing to hand back: the function changes the string in place, and name stays the owner the whole time.
Three muts in one program
For a function to change your string, you write the word mut three times:
let mut name: the owner allows the string to change;s: &mut String: the function declares that it will change it;add_mark(&mut name): the call explicitly lends the string for writing.
The last one is especially useful: the call line shows at once that the function may change name, with no need to look inside the function.
Writing through *
You call a method through &mut without a star, as through &: the dot finds the value on its own. But to replace the whole value — assign a new one or add to a number — you have to dereference the reference. Dereferencing is going from a reference to the value itself, and it is written with a star: *n.
fn add_one(n: &mut i32) {
*n += 1;
}
fn main() {
let mut score = 10;
add_one(&mut score);
add_one(&mut score);
println!("{score}"); // 12
}Let's go step by step:
add_onegets a mutable reference to a number.*n += 1follows the reference toscoreitself and adds one to it.- Two calls increase
scoretwice, andprintln!prints12.
Without the star, n += 1 tries to add a number to the reference itself, and the compiler answers with error E0368. An i32 is a Copy type, but through &mut the function changes not a copy but the calling code's variable.
Here the book analogy falls short. In real life anyone holding the book can write in the margins. In Rust you can change a value through a reference only if the owner allowed it with the word mut in the declaration.
Interviewers like to ask this: "How does & differ from &mut?" The answer:
- through
&you can only read the value, through&mutyou can also change it; - you can take a
&mutonly from a variable declared withmut; - neither reference takes ownership;
- changes made through
&mutare visible to the owner after the call, because the reference points to the value itself, not to a copy.
Common mistake
A mutable reference is taken from a variable declared without mut:
fn add_mark(s: &mut String) {
s.push('!');
}
fn main() {
let name = String::from("Anna");
add_mark(&mut name); // ✗
println!("{name}");
}error[E0596]: cannot borrow `name` as mutable, as it is not declared as mutableThe program does not compile: let without mut promises that the value will not change, and you cannot get around that promise through a reference. This is a compile error, not a panic, and the program never gets to run. The compiler suggests the fix: let mut name.
Key points
&mut namegives a mutable reference: through it a function changes someone else's value without taking ownership.- You can take a mutable reference only from a variable with
mut, otherwise you get error E0596. - You call methods through
&mutwithout a star, and write a new value through*n. - A
&mutpoints to the variable itself, so the owner sees every change.