Rust forbids two mutable references to the same data simultaneously to guarantee memory safety and prevent data races at compile time.
Rust prevents two mutable references to the same data to avoid data races and undefined behavior at compile time. You can only have one mutable reference or multiple immutable references at any given time.
fn main() {
let mut data = 5;
let r1 = &mut data;
// let r2 = &mut data; // This line would cause a compile error
*r1 = 10;
}
The rule against two mutable references in Rust ensures that only one part of your code can change a piece of data at a time, preventing confusing bugs where two parts try to change it simultaneously. Think of it like a library book: only one person can check it out to write in it, while others can only read it if no one is writing.