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

The Rules of Exclusive Mutability

Enforce the constraint that you may have either one mutable reference or infinite immutable ones.

In this lesson, you will learn the fundamental "golden rule" of Rust that prevents data corruption: the choice between shared reading and exclusive writing.

The Two Paths of Access

Up until now, you have seen how to create immutable references (&T) to look at data. You can have as many of these as you want simultaneously because reading data is safe—no one is changing the underlying value while you’re looking at it.

However, when you need to change data, you must use a mutable reference (&mut T). Rust introduces a strict rule to ensure memory safety: You may have either one mutable reference or any number of immutable references, but never both at the same time.

Why does this rule exist?

Think of your data as a document. If ten people are reading it (immutable references), that is fine. But if someone starts editing that document (mutable reference) while others are reading it, the readers might see a half-finished sentence or get confused by the sudden changes.

Rust’s "Borrow Checker" enforces this strictly at compile time:

fn main() {
    let mut data = String::from("Hello");

    let r1 = &data; // Immutable borrow
    let r2 = &data; // Another immutable borrow
    
    // This would cause a compiler error:
    // let m1 = &mut data; 

    println!("{} and {}", r1, r2);
}

In the example above, if you tried to create m1 while r1 or r2 were still in use, the compiler would stop you. You must finish using your immutable references before you can create a mutable one, or vice-versa.

The Concept of Exclusivity

"Exclusive" means that when you have a mutable reference, you are the only one allowed to touch that data. No one else can have a reference (mutable or immutable) to that data until you are finished. This eliminates "data races" at the compiler level. By forcing you to choose between "many readers" or "one writer," Rust guarantees that your data will never change unexpectedly while you are relying on its current state.

Key Takeaway: You may have infinite immutable references OR exactly one mutable reference at any given time, but you can never have both.