Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ OWNERSHIP WITHOUT THE PANIC
BUILD NOTE 12 / 53

One writer at a time.

Use exclusive borrowing to update values safely.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

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.

lessons/mutable-borrows/src/main.rs
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]);
}
↳ EXPECTED OUTPUT
server ready
2 6
  1. 1

    The owner is declared mut because it will be changed.

  2. 2

    The function receives a temporary exclusive borrow.

  3. 3

    The later print runs after the mutation borrow has ended.

From the extracted rust-workbench folder
cargo run -p lesson_mutable_borrows

03 Mind the boundary

04 Your next build

A SMALL MISSION

Use split_at_mut to change the first element of both halves of an array.

Reveal one possible solution +
solutions/mutable-borrows/src/main.rs
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

QUICK SIGNAL CHECK

Can two conflicting active &mut references access the same value?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.