In this lesson, you will learn how to safely obtain exclusive write access to data using Rust’s strict borrowing rules.
So far, we have looked at how to share data using immutable references (&T). These allow many parts of your code to read the same data simultaneously. However, if you need to change that data, you must use a mutable reference (&mut T).
To prevent data races—where two parts of a program try to modify the same memory at the same time—the Rust compiler enforces a very specific rule for mutable references: You can have exactly one mutable reference to a piece of data in any given scope.
The "Exclusive Access" Rule
Think of a mutable reference as a "key" to a room. If you hold the only key, you can safely rearrange the furniture (modify the data) without worrying about someone else walking in and moving things while you are in the middle of it. If Rust allowed two mutable references at once, the compiler couldn't guarantee that the data stays consistent.
Consider this example:
fn main() {
let mut data = 10;
let r1 = &mut data; // We borrow data mutably
*r1 += 5; // We modify it through the reference
// let r2 = &mut data; // ERROR: Cannot borrow `data` as mutable more than once
println!("The value is: {}", *r1);
}
In the commented-out line, the borrow checker would stop you. Even though you are the only one holding a mutable reference, asking for a second one while the first one is still "active" is forbidden.
Why is this enforced?
By ensuring that a mutable reference is exclusive, Rust guarantees that no other part of your program is reading or writing that memory while you are working on it. This eliminates an entire class of bugs where data changes unexpectedly beneath your feet. To get a new mutable reference, the previous one must reach the end of its scope, effectively "returning the key" so someone else can use it.
Key Takeaway: You can have either multiple immutable references OR exactly one mutable reference at any time, but never both at once.