skip to content

In Rust, why does `match self.state { State::Retrying { mut attempts, .. } => attempts += 1, _ => {} }` leave the stored count unchanged, and how do you fix it?

level: seniorimportance: should knowfreq 35%

answer

  1. is the scrutinee a place or a reference?
  2. move mode copies a Copy field
  3. mut makes the local mutable, not the field
  4. &mut scrutinee or ref mut

basics

~20 s

self.state is a place of type State, not a reference, so binding starts in move mode and mut attempts copies the u32 into a new mutable local. Match on &mut self.state, or write ref mut attempts, to bind a &mut u32 instead.

solid answer

~50 s

A pattern binds by the **default binding mode**, and that depends on the scrutinee's type. `self.state` names the field itself, of type `State`, so the mode is **move**: `attempts` binds by value, and because `u32` is `Copy` that is a copy. `mut` only makes that local copy mutable, so `attempts += 1` changes the copy, and rustc's only hints are the `unused_variables` and `unused_assignments` warnings. Two fixes: match on `&mut self.state`, so the non-reference pattern meets a `&mut State`, the mode becomes `ref mut`, and `attempts` is a `&mut u32` you update with `*attempts += 1`; or keep `self.state` and write `ref mut attempts` explicitly. The same move mode makes a `String` field fail with E0507 instead of copying. On the 2024 edition, writing `mut attempts` while matching `&mut self.state` is rejected outright, where earlier editions copied again with only warnings.

code

rust · 42 lines
rust
#[derive(Debug)]
enum State { Idle, Retrying { attempts: u32, last_error: String } }

struct Worker { state: State }

impl Worker {
    // Bug: `attempts` binds a copy of the field; the increment is lost.
    fn record_failure_buggy(&mut self) {
        match self.state {
            State::Retrying { mut attempts, .. } => attempts += 1,
            State::Idle => {}
        }
    }
    // Fix 1: match on `&mut self.state`; the default binding mode becomes `ref mut`.
    fn record_failure(&mut self, err: &str) {
        match &mut self.state {
            State::Retrying { attempts, last_error } => {
                *attempts += 1;               // attempts: &mut u32
                *last_error = err.to_string(); // last_error: &mut String
            }
            State::Idle => {}
        }
    }
    // Fix 2: keep the place scrutinee and ask for a mutable borrow explicitly.
    fn reset(&mut self) {
        if let State::Retrying { ref mut attempts, .. } = self.state {
            *attempts = 0;
        }
    }
}

fn main() {
    let mut w = Worker { state: State::Retrying { attempts: 1, last_error: String::new() } };
    w.record_failure_buggy();
    println!("{:?}", w.state); // attempts: 1
    w.record_failure("timeout");
    println!("{:?}", w.state); // attempts: 2
    w.reset();
    println!("{:?}", w.state); // attempts: 0
    w.state = State::Idle;
    w.record_failure("ignored");
}

go deeper

for a junior

Recall that a pattern binding copies a Copy value unless the scrutinee is a reference, and that mut on a binding makes a new mutable variable.

for a middle

Walk through the binding-mode steps, move then ref then ref mut, and give the type of attempts for self.state, &self.state and &mut self.state.

for a senior

Diagnose the lost update from the unused_assignments warning, choose between matching on &mut and an explicit ref mut, and know that 2024 now rejects mut under an implicit borrow.

for a principal

No lead decision lives here; at most, a team habit of denying unused_assignments in CI and preferring &mut scrutinees for mutating matches.

## What the pattern actually binds A `match` compares a **scrutinee** with patterns. Here the scrutinee is `self.state`. Even inside a `&mut self` method, `self.state` is a **place expression** of type `State`: it names the field, it is not a reference to it. The pattern `State::Retrying { mut attempts, .. }` therefore matches a `State` directly. When a binding has no `ref` or `ref mut`, it uses the **default binding mode**, which starts as **move**. In move mode a binding takes the value itself: - a `Copy` field such as `attempts: u32` is **copied** into the new variable; - a non-`Copy` field such as `last_error: String` would be **moved**, which out of `&mut self` is E0507, "cannot move out of `self.state.last_error` as enum variant `Retrying` which is behind a mutable reference". The `mut` in `mut attempts` is a property of the **new local variable**, not of the field. `attempts += 1` increments the local copy, which is dropped at the end of the arm. rustc compiles it with two warnings, "variable `attempts` is assigned to, but never used" (`unused_variables`) and "value assigned to `attempts` is never read" (`unused_assignments`); in a crate that tolerates warnings, the bug ships. ## Default binding modes on a reference scrutinee Match ergonomics change the mode when a **non-reference pattern** (a struct, enum, tuple, slice or literal pattern) meets a reference: 1. The mode starts as **move**. 2. Meeting a `&T` dereferences it and sets the mode to **`ref`**. 3. Meeting a `&mut T` dereferences it and sets the mode to **`ref mut`**, unless it is already `ref`, in which case it stays `ref`. 4. Each binding without an explicit mode uses the current one. So `match &mut self.state { State::Retrying { attempts, last_error } => ... }` binds `attempts: &mut u32` and `last_error: &mut String`. Both now point into `self.state`: `*attempts += 1` updates the stored count and `*last_error = err.to_string()` replaces the stored message. Nothing is copied or moved. The same fix applies when the method receives the state as a parameter: with `state: &mut State`, `match state { State::Retrying { attempts } => *attempts += 1, ... }` already meets a `&mut State`, so writing nothing extra gives a `&mut u32`. The rule never looks at how `self` was received; it looks only at the type of the expression after `match`, and at each layer of reference the pattern passes on the way in. | Scrutinee | Pattern binding | `attempts` is | Effect of the update | |---|---|---|---| | `self.state` | `mut attempts` | `u32`, a copy | lost at the end of the arm | | `&mut self.state` | `attempts` | `&mut u32` | `*attempts += 1` updates the field | | `self.state` | `ref mut attempts` | `&mut u32` | `*attempts += 1` updates the field | | `&self.state` | `attempts` | `&u32` | read only | ## Explicit `ref` and `ref mut` `ref` and `ref mut` ask for a borrow regardless of the default mode. They are what you write when the scrutinee is a **place** and you want a reference rather than a copy or a move: `if let State::Retrying { ref mut attempts, .. } = self.state { *attempts = 0; }`. The Rust Reference puts it plainly: `ref` "is not something that is being matched against"; it only changes how the binding is made. They also let one pattern mix modes, borrowing one field while copying another; moving one field out while borrowing another leaves a **partial move**, which is covered with ownership. ## The 2024 edition rule, in brief When the default mode is already `ref` or `ref mut`, Rust 2024 rejects an explicit `mut`, `ref` or `ref mut` on a binding, and a `&` or `&mut` reference pattern; they may appear only in the fully explicit part of a pattern. So `match state { State::Retrying { mut attempts } => ... }` with `state: &mut State` fails on edition 2024 with "cannot mutably bind by value within an implicitly-borrowing pattern"; on edition 2021 and earlier that `mut` reset the mode to move without any error and reproduced the copy bug. Edition migration itself is covered with editions. ## Reviewing a pattern that mutates - Ask what the scrutinee's type is: a place, a `&` or a `&mut`. - Treat `mut name` inside a pattern as a red flag when the intent is to change the original. - Prefer matching on `&mut` and dereferencing with `*`; it states the intent in the scrutinee. - Do not silence `unused_assignments` in a pattern arm; it is often this bug. - Remember the asymmetry: the copy bug compiles with warnings for `Copy` fields, while the same pattern on a `String` field fails with E0507, so a struct whose fields change type can flip from one to the other.

  • Why does `match self.state { State::Retrying { last_error, .. } => ... }` in a `&mut self` method fail instead of copying?
    The mode is move, and `String` is not `Copy`, so binding `last_error` would move it out of a struct you only borrow. rustc reports E0507, "cannot move out of `self.state.last_error` as enum variant `Retrying` which is behind a mutable reference", and suggests `ref last_error`. Matching on `&self.state` or `&mut self.state` borrows instead.
  • When a pattern passes through both a `&` and a `&mut`, as when matching a `&mut &State` or a `&&mut State`, which mode do the bindings get?
    `ref` in both cases, so `attempts` is a `&u32`. A `&` always sets the mode to `ref`, and a `&mut` sets `ref mut` only when the mode is not already `ref`. Once a shared reference has been passed on the way in, nothing below it can be borrowed mutably, which is exactly what a shared reference promises.
  • Why does Rust 2024 reject `ref` on a binding when matching `&opt`, as in `if let Some(ref name) = &opt`?
    The default mode is already `ref`, so the explicit `ref` is redundant, and the 2024 edition reserves explicit binding modes for the fully explicit part of a pattern. rustc reports "cannot explicitly borrow within an implicitly-borrowing pattern" and suggests removing `ref`; `cargo fix --edition` makes that change for you.

Copying a number from a shared spreadsheet onto a sticky note and adding one to the note: the spreadsheet still shows the old value. Matching on &mut self.state is putting the cursor in the cell and editing it there.

  • `mut attempts` in a pattern makes the matched field mutable in place.
  • Inside a `&mut self` method, `match self.state` already matches through a reference.
  • rustc rejects the copy bug with an error, so it cannot reach a build.
  • `ref mut` is obsolete now that match ergonomics exist.
  • Matching on `&mut self.state` moves the `String` fields out.

Assumes Rust 1.99 on the 2024 edition (stable since 1.85), which rejects an explicit mut, ref or ref mut binding under a ref or ref mut default binding mode; earlier editions accepted it.