← Back to Rust Course | Chapter 6: Borrowing & References | Lesson 2 of 6

Mutable References

A mutable reference lets someone borrow your value and actually change it, but only one person can hold that permission at a time.

Creating a Mutable Reference

Writing &mut value creates a reference that is allowed to modify the data it points to. The variable being referenced must itself have been declared with mut.

Example: Creating a Mutable Reference

markup
fn add_exclamation(s: &mut String) {
    s.push_str("!");
}

fn main() {
    let mut message = String::from("Hello");
    add_exclamation(&mut message);
    println!("{}", message);
}

Only One Mutable Reference at a Time

Rust enforces that at most one mutable reference to a value can exist within a given scope, preventing two pieces of code from unexpectedly changing the same data at once.

Note: Notice r1's scope ends before r2 is created -- that's what makes this compile.

Example: Only One Mutable Reference at a Time

markup
fn main() {
    let mut count = 5;
    {
        let r1 = &mut count;
        *r1 += 1;
    }
    let r2 = &mut count;
    *r2 += 1;
    println!("count = {}", count);
}

Cannot Mix Mutable and Immutable References

You cannot hold a mutable reference at the same time as any immutable references to the same value, since a reader could otherwise see the data change unexpectedly mid-read.

Example: Cannot Mix Mutable and Immutable References

markup
fn main() {
    let mut value = 10;
    {
        let readable = &value;
        println!("Read before mutation: {}", readable);
    }
    let writable = &mut value;
    *writable += 5;
    println!("After mutation: {}", value);
}

Dereferencing to Modify

To change the value behind a mutable reference, use the dereference operator * to access the underlying data directly.

Example: Dereferencing to Modify

markup
fn double(n: &mut i32) {
    *n *= 2;
}

fn main() {
    let mut x = 7;
    double(&mut x);
    println!("x is now {}", x);
}
Common Mistakes
  1. Trying to create two mutable references to the same value in the same scope, which the borrow checker forbids.
  2. Mixing a mutable reference and an immutable reference to the same value at the same time.
  3. Forgetting mut on both the original variable and the reference itself when creating a mutable reference.
Chapter Summary
  • A mutable reference is written &mut value and allows modifying the borrowed data.
  • Only one mutable reference to a particular value can exist at a time within its scope.
  • You cannot have a mutable reference and any immutable references active at the same time.
  • The original variable must itself be declared with mut before it can be mutably borrowed.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.