The Borrowing Rules Demystified
The Borrowing Rules Demystified
Rust’s compiler enforces two fundamental rules regarding references at compile time:
- At any given time, you can have either one mutable reference or any number of immutable references.
- References must always be valid.
Why the Rules Exist
This rule (often summarized as Aliasing XOR Mutability) prevents data races. A data race occurs when: - Two or more pointers access the same memory concurrently. - At least one pointer is writing. - There is no synchronization.
By disallowing simultaneous reading and writing through multiple aliases, Rust eliminates data races before the code ever compiles.