Note that this article asserts the Rust 2024 edition.

I’ve been learning Rust recently and this example from a rustlings exercise got me confused:

let mut job_status: std::sync::MutexGuard<'_, JobStatus> = status_shared.lock().unwrap_or_else(|e| e.into_inner());
job_status.jobs_done += 1;

Context: we need multiple threads to update a shared value, so we lock the std::sync::Mutex, unwrap into a std::sync::MutexGuard and increment the shared value through it.

My confusion was why a mut binding is needed for the MutexGuard job_status since it’s only a pointer to the actual mutex and we’re not modifying the pointer itself anyway. Intuitively it feels like we only need a mut reference not a mut binding for stuff like this.

To address this we need to understand the exact meaning of mut first.

Two kinds of mut#

Rust syntax overloads mut across two distinct concepts that I will refer to as “mutable binding” and “mutable reference”.

Mutable binding#

A mutable binding is a variable binding that explicitly allows:

  • Reassigning the variable’s value. (Regardless of its type.)
  • Taking a mutable reference.

E.g.:

let mut a = 1;
a = 2;                  // Reassigning is allowed.
let mut_ref_a = &mut a; // Taking mutable reference is allowed.

In our rustlings example, let mut job_status ... is a mutable binding to the MutexGuard.

Mutable reference#

A mutable reference is a distinct type that makes these guarantees:

  • The referenced memory location is valid and write is allowed.
  • It’s the only accessible path (no other read or write paths) to the referenced memory location during its scope.

E.g.:

let mut a = 1;
let mut_ref_a = &mut a;
*mut_ref_a = 2;         // Always works.
let mut b = 1;
let ref_b = &b;
let mut_ref_b = &mut b; // Doesn't compile. Another path to b exists.

This is what we conceptually want in the rustlings example - the ability to modify the referenced shared value.

Dereference guarantees#

In Rust, variables whose types implement the DerefMut trait can be used for mutable dereferencing operations, like in *v = 11:

pub trait DerefMut: Deref {
    // Required method
    fn deref_mut(&mut self) -> &mut Self::Target;
}

Since only mutable bindings allow taking mutable references, any variable being mutably dereferenced must be a mutable binding, although the returned mutable reference does not point to the binding itself. This is to guarantee the uniqueness of mutable references.

For an example, imagine if DerefMut is like this:

trait DerefMut {
   fn deref_mut(&self) -> &mut Self::Target;
}

Then we could do:

let mg = mu.lock().unwrap();
let a = mg.deref_mut();
let b = mg.deref_mut();      // Compiles since receiver is not mut.
// Now we have two mutable references to the same memory.

In our example, job_status.jobs_done += 1; performs a mutable dereference on a MutexGuard. Therefore job_status must be a mutable binding even though it does not need to be modified. This is exactly the Rust compiler’s mechanism to guarantee exclusive access.

Footnotes#

  1. https://doc.rust-lang.org/std/ops/trait.DerefMut.html. ↩