A shared borrow lets a function read text. Sometimes a function needs to change the caller's value instead: mark a topic as planned, append a status, increase a counter. Moving the String in and returning it would work, but Rust has a direct way. A mutable reference, written &mut, lends a value with permission to change it. A function with a &mut String parameter can call methods that modify the original text, such as push_str.
That permission comes with one rule, which the compiler enforces: at any moment, a value can have either any number of shared borrows or exactly one mutable borrow, never both. The reason is simple. If one part of the program is reading the text while another part is changing it, the reader can see something half-finished. Appending to a String may even move its text to a larger area of memory, leaving an old view pointing at nothing. Rust rules this out before the program runs.
Predict and run
The caller's binding must be declared with let mut, and the call passes &mut title. Which string gets the suffix? What will main print?
fn add_label(topic: &mut String) {
topic.push_str(" (planned)");
}
fn main() {
let mut title = String::from("Rust");
add_label(&mut title);
println!("{title}");
}Check your prediction
Rust (planned)There is only one String in this program. add_label changed it through the reference, so main sees the new text. Now try to keep a shared view across the call:
fn main() {
let mut title = String::from("Rust");
let view = &title;
add_label(&mut title);
println!("{view}");
}This fails with error[E0502]: cannot borrow title as mutable because it is also borrowed as immutable. The compiler marks where view was created, where the mutable borrow starts and where view is later used. Move the let view line and its println! after the call, and it compiles.
A borrow ends at its last use
A borrow does not last until the closing brace. It lasts only until the last line that uses the reference. That is why the reordered version works, and why several shared borrows followed by a mutable one are fine as long as they do not overlap.
fn main() {
let mut title = String::from("Rust");
let first = &title;
let second = &title;
println!("{first} / {second}");
let editor = &mut title;
editor.push_str(" basics");
println!("{title}");
}Rust / Rust
Rust basicsTwo shared borrows read the text at the same time, which is always safe. Their last use is the first println!, so by the time editor is created, no reader remains. editor is last used on the push_str line, so main can print title directly afterward.
Every step says mut
A change through a borrow needs mut in three places: the owner's binding (let mut), the call (&mut title) and the parameter type (&mut String). Leave one out and the compiler tells you which:
- Without
let mut:error[E0596]: cannot borrow title as mutable, as it is not declared as mutable. - With
&titleat the call:error[E0308]: mismatched types, noting that the types differ in mutability.
The same works for numbers. To change an i32 through a reference, put * in front of the reference. *count means "the value that count refers to". String methods like push_str do this for you, but arithmetic needs it written out.
fn add_session(count: &mut i32, minutes: i32) {
if minutes >= 15 {
*count += 1;
}
}
fn main() {
let mut sessions = 0;
add_session(&mut sessions, 25);
add_session(&mut sessions, 10);
add_session(&mut sessions, 30);
println!("Sessions: {sessions}");
}Sessions: 2Without the *, count += 1 fails with error[E0368]: binary assignment operation += cannot be applied to type &mut i32: you cannot add one to a reference, only to the number it points to.
Ask for the least access you need
Use &str when a function only reads text and &mut String only when it must change it. The parameter type then tells every caller exactly what the function may do to their value.
Practice
Your turn
Write a function mark_done that appends [done] to the caller's title and returns nothing. Call it from main before the println!, so the program prints Rust [done]. You will need to change main as well as write the function: count the places that must say mut.
// Write mark_done here.
fn main() {
let title = String::from("Rust");
// Call mark_done here.
println!("{title}");
}Hint 1: the idea
The function must change the caller's String without taking it, so it needs a mutable borrow. A mutable borrow is only possible from a binding that allows change, and the call has to ask for it.
Hint 2: a first step
Write the signature first. Of String, &String and &mut String, pick the parameter type that lets the function change text it does not own. Then run the program: the compiler's errors point at what main still needs.
Worked solution
fn mark_done(topic: &mut String) {
topic.push_str(" [done]");
}
fn main() {
let mut title = String::from("Rust");
mark_done(&mut title);
println!("{title}");
}Rust [done]All three muts are needed: let mut title, &mut title at the call and &mut String in the signature. The function edits the same String that main prints; nothing was copied or returned. Calling mark_done twice would append the suffix twice, because the function does not check what is already there. The checkpoint asks you to handle exactly that case.
Completion is saved in this browser only. It does not measure mastery.