One writer at a time.
Use exclusive borrowing to update values safely.
01 Understand the contract
A mutable reference &mut T grants exclusive access for the duration of that active borrow. You cannot simultaneously use a conflicting shared or mutable reference. The rule is about aliasing plus mutation, not about banning all mutation. Once a borrow’s last use has passed, the owner can be accessed again. Keep mutable borrows short and near the operation they support. If you need disjoint parts of a collection, use APIs such as split_at_mut that express the non-overlap to the compiler.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn append_ready(text: &mut String) {
text.push_str(" ready");
}
fn main() {
let mut task = String::from("server");
append_ready(&mut task);
let values = [1, 2, 3, 4].map(|n| n * 2);
let (left, right) = values.split_at(2);
println!("{task}");
println!("{} {}", left[0], right[0]);
}server ready 2 6
- 1
The owner is declared mut because it will be changed.
- 2
The function receives a temporary exclusive borrow.
- 3
The later print runs after the mutation borrow has ended.
cargo run -p lesson_mutable_borrows03 Mind the boundary
04 Your next build
Use split_at_mut to change the first element of both halves of an array.
Reveal one possible solution +
fn main() {
let mut values = [1, 2, 3, 4];
let (left, right) = values.split_at_mut(2);
left[0] = 10;
right[0] = 30;
assert_eq!(values, [10, 2, 30, 4]);
}05 Check your reasoning
Can two conflicting active &mut references access the same value?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.