Course contentsShow
← Rust
Lesson 26 of 1,9101. Rust Fundamentals and ToolingFree lesson

Mutable and Immutable Aliasing

Implement strict aliasing rules that prevent data races at compile time.

In this lesson, you will learn how Rust’s strict aliasing rules prevent data races by enforcing specific permissions on how you can access your data.

The Rule of Access

In Rust, the compiler enforces two fundamental rules regarding references to ensure memory safety:

  1. You can have as many immutable references (&T) as you want. These are "read-only" views of data.
  2. You can have exactly one mutable reference (&mut T) at a time. This is an "exclusive" view of data.

You might wonder why we can't have a mutable reference while others are reading, or multiple mutable references at once. This is to prevent aliasing hazards. If you have two mutable references to the same piece of data, one part of your code could change the value while another part is expecting it to stay the same. This leads to unpredictable bugs and "data races," where the state of your program becomes non-deterministic.

Seeing it in Action

Consider this scenario where we try to break the rules:

fn main() {
    let mut data = 10;
    
    let r1 = &data;    // Immutable reference 1
    let r2 = &data;    // Immutable reference 2 (Allowed!)
    
    let m1 = &mut data; // ERROR: Cannot borrow as mutable because it is already borrowed
    
    println!("{}, {}, {}", r1, r2, m1);
}

The compiler stops you here. It sees that data is currently being "aliased" by immutable references (r1 and r2). To grant a mutable reference, Rust requires exclusive access. Because the data is currently being read, Rust denies the mutable request to prevent you from changing the data out from under the readers.

Why this matters

By enforcing these rules at compile time, Rust eliminates an entire class of bugs that plague languages like C++. You don't have to worry about accidentally modifying a variable while a different part of your program is still using its old value. If your code compiles, you are guaranteed that no other part of your program is holding an conflicting reference.

Key Takeaway: Rust allows either many immutable references OR one exclusive mutable reference at any given time, but never both, ensuring your data remains stable and race-free.