Course contentsShow
← Rust
Lesson 215 of 1,9103. Borrowing and ReferencesFree lesson

Differentiating Mutability of Bindings and References

Clarify the difference between a mutable variable and a mutable reference to an immutable variable.

In this lesson, you will learn how to distinguish between changing a variable's binding and changing the data that a reference points to.

The Immutable Binding

When you declare a variable in Rust, it is immutable by default. This is called an immutable binding. Even if the data itself is theoretically changeable, the variable name is "locked" to the value you first assigned to it.

let x = 5;
x = 6; // Error! You cannot reassign an immutable binding.

The Mutable Binding

If you add mut to the variable, you create a mutable binding. This allows you to point that name to a new value later. However, notice that this is separate from the data being referenced.

let mut x = 5;
x = 6; // This is perfectly fine.

The Mutable Reference

Now, consider a scenario where you have an immutable binding to a variable, but you want to change the data inside it. You can do this by using a mutable reference.

Even if my_data is immutable, if we borrow it mutably, we gain the right to modify the data behind the scenes. The "binding" (the name my_data) remains fixed, but the "referenced data" changes.

let mut data = 10;
let my_data = &mut data; // my_data is a mutable reference to data

*my_data = 20; // We change the value of 'data' via the reference

Why does this matter?

The confusion often arises because people think mut always means "the thing can change." In Rust, we have two distinct layers:

  1. The Binding: Can this variable name point to a different piece of memory? (Controlled by let vs let mut)
  2. The Reference: Does this pointer give me permission to modify the memory it points to? (Controlled by & vs &mut)

You can have an immutable binding that holds a mutable reference, allowing you to modify the underlying data while keeping the reference itself fixed. Conversely, you can have a mutable binding that holds an immutable reference, which you can swap out to point at entirely different, read-only data.

Key Takeaway: A mutable binding allows you to reassign the variable to a new location, while a mutable reference allows you to modify the data at the location currently being pointed to.