Course contentsShow
← Rust
Lesson 213 of 1,9103. Borrowing and ReferencesFree lesson

Mutable Borrowing Constraints

Identify the code patterns that trigger borrow checker errors regarding simultaneous mutable access.

In this lesson, you will learn why Rust forbids having multiple mutable references to the same data at the same time.

The Rule of One

In the world of Rust, the borrow checker enforces one strict rule: You can have exactly one mutable reference to a specific piece of data in a particular scope.

Think of a mutable reference like a "write-lock" on a document. If you grant multiple people the ability to edit a document simultaneously, you invite chaos—one person might delete a paragraph while another is adding a sentence, leading to corrupted data. Rust prevents this "data race" at compile time.

The Forbidden Pattern

Consider this scenario where we try to create two mutable references at once:

fn main() {
    let mut score = 10;

    let ref1 = &mut score;
    let ref2 = &mut score; // Error!

    *ref1 += 5;
    *ref2 += 10;
}

When the compiler reaches the definition of ref2, it stops you. Even though both references are for the same variable, the compiler sees that you are attempting to create a second "write-lock" while the first one is still active.

Why This Matters

This restriction ensures that your program’s state remains predictable. If you have a mutable reference, you are guaranteed that no other part of the code is currently modifying or even reading that data through another reference. This eliminates an entire class of bugs common in other languages, such as "iterator invalidation" (where a list changes size while you are trying to loop through it) or silent memory corruption.

To fix the error above, you must ensure that the first mutable reference goes out of scope before creating the second:

let mut score = 10;
{
    let ref1 = &mut score;
    *ref1 += 5;
} // ref1 goes out of scope here

let ref2 = &mut score; // This is now allowed!
*ref2 += 10;

By controlling the lifespan of your mutable references, you ensure that only one "writer" is active at any given moment.

Key Takeaway: You can have many immutable references, or exactly one mutable reference, but never both at once or multiple mutable ones simultaneously.