Sub topic 14
Modeling states and commands with enums
This chapter assumes you can define enums with data-carrying variants, write match expressions with guards and @ bindings, and understand moves versus borrows. It applies those pieces to one design problem. You describe what a system can be (its states) and what can happen to it (its commands), and you let the compiler check the combinations.
Why enums fit state machines
A state machine is a system that is always in exactly one of a fixed set of states, and moves between them in response to events. Many programs contain one: a network connection, a parser, a UI screen, an order workflow.
A common first attempt uses a struct of flags:
struct Connection {
is_connected: bool,
is_connecting: bool,
session_id: Option<u64>,
error: Option<String>,
}This struct can represent combinations that make no sense. It can be is_connected and is_connecting at once, or connected with no session_id, or hold an error while connected. Every function that touches it must defend against those cases, and nothing enforces that it does.
An enum makes the valid states the only states. Each variant carries exactly the data that makes sense in that state:
Idlecarries nothing.Connectingcarries an attempt counter.Connectedcarries a session id that always exists.Failedcarries a reason that always exists.
The type State cannot hold a session id while idle, because no variant allows it. This is often summarized as "make invalid states unrepresentable".
Commands as a second enum
The events that drive transitions are also a closed set, so they work well as an enum. Each command carries the payload it needs, such as a session id or an error message.
A transition function that matches on both enums
The core of the pattern is one function that takes the current state and a command and returns the next state. Matching on the tuple (self, cmd) lets a single match see both values at once.
#[derive(Debug)]
enum State {
Idle,
Connecting { attempts: u32 },
Connected { session_id: u64 },
Failed { reason: String },
}
#[derive(Debug)]
enum Command {
Connect,
Succeeded(u64),
Fail(String),
Disconnect,
}
impl State {
fn next(self, cmd: Command) -> State {
match (self, cmd) {
(State::Idle, Command::Connect) => State::Connecting { attempts: 1 },
(State::Connecting { .. }, Command::Succeeded(id)) => {
State::Connected { session_id: id }
}
(State::Connecting { attempts }, Command::Fail(_)) if attempts < 3 => {
State::Connecting { attempts: attempts + 1 }
}
(State::Connecting { .. }, Command::Fail(reason)) => State::Failed { reason },
(State::Connected { .. }, Command::Disconnect) => State::Idle,
(State::Failed { .. }, Command::Connect) => State::Connecting { attempts: 1 },
(state, _) => state,
}
}
}
fn main() {
let mut state = State::Idle;
let commands = [
Command::Connect,
Command::Fail("timeout".to_string()),
Command::Succeeded(42),
Command::Disconnect,
];
for cmd in commands {
println!("{cmd:?}");
state = state.next(cmd);
println!(" -> {state:?}");
}
}Several details in this code are worth reading closely.
nexttakesselfby value. The old state is consumed, so no code can keep using a state that no longer exists. Data moves from the old state into the new one, asreasondoes in theFailedarm, without cloning.- The guard splits one event into two outcomes.
FailonConnectingeither retries or gives up, depending onattempts. The two arms are ordered, so the guarded arm must come first. - The final arm
(state, _) => stateis a deliberate choice. It says that any combination not listed leaves the state unchanged. ADisconnectwhileIdleis ignored.
Running the program prints Connecting { attempts: 1 }, then Connecting { attempts: 2 }, then Connected { session_id: 42 }, then Idle.
Catch-all arms and exhaustiveness
The (state, _) arm has a cost. Exhaustiveness checking is what normally tells you where to update code after adding a variant. A wildcard arm hides that signal.
Suppose you add a Command::Reset later. With the catch-all arm, the code still compiles and Reset is silently ignored. That may be what you want or it may be a bug, and the compiler will not tell you which.
You have two options:
- Keep the catch-all and accept that new commands default to "ignored". This suits machines where most combinations really are no-ops.
- List every combination explicitly. This is verbose, but each new variant then forces you to decide what it does in every state.
Rejecting invalid transitions with Result
Ignoring invalid commands hides mistakes. When callers should know a command was refused, return a Result. Because apply consumes the old state, the error case hands the state back, so the caller does not lose it.
#[derive(Debug)]
enum Door {
Open,
Closed,
Locked { code: u32 },
}
#[derive(Debug)]
enum DoorCmd {
Open,
Close,
Lock(u32),
Unlock(u32),
}
#[derive(Debug)]
enum DoorError {
AlreadyOpen,
MustUnlockFirst,
WrongCode,
}
impl Door {
fn apply(self, cmd: DoorCmd) -> Result<Door, (Door, DoorError)> {
match (self, cmd) {
(Door::Closed, DoorCmd::Open) => Ok(Door::Open),
(Door::Open, DoorCmd::Close) => Ok(Door::Closed),
(Door::Closed, DoorCmd::Lock(code)) => Ok(Door::Locked { code }),
(Door::Locked { code }, DoorCmd::Unlock(attempt)) if code == attempt => {
Ok(Door::Closed)
}
(door @ Door::Locked { .. }, DoorCmd::Unlock(_)) => {
Err((door, DoorError::WrongCode))
}
(door @ Door::Locked { .. }, DoorCmd::Open) => {
Err((door, DoorError::MustUnlockFirst))
}
(door @ Door::Open, DoorCmd::Open) => Err((door, DoorError::AlreadyOpen)),
(door, _) => Ok(door),
}
}
}
fn main() {
let mut door = Door::Closed;
let commands = [
DoorCmd::Lock(1234),
DoorCmd::Open,
DoorCmd::Unlock(1),
DoorCmd::Unlock(1234),
DoorCmd::Open,
];
for cmd in commands {
door = match door.apply(cmd) {
Ok(next) => next,
Err((same, e)) => {
println!("refused: {e:?}");
same
}
};
println!("{door:?}");
}
}The door @ Door::Locked { .. } bindings use the @ pattern from earlier in this tutorial. They test the shape of the state and also capture the whole value, so it can be returned in the Err. The program prints Locked { code: 1234 }, then refused: MustUnlockFirst and Locked { code: 1234 }, then refused: WrongCode and Locked { code: 1234 }, then Closed, then Open.
Note that the code stored in Locked exists only in that variant. An open door has no code to leak or forget to clear.
Design choices and trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Data inside variants | Impossible states cannot be built | Moving data between variants needs ownership transfers |
| `next(self, ...)` by value | Old state cannot be reused by mistake | Callers must reassign, and errors must return the old state |
| `next(&mut self, ...)` | No reassignment at the call site | You must replace `*self` carefully, often with `std::mem::replace` |
| Catch-all arm | Short code for sparse machines | New variants are ignored without a compiler warning |
| Explicit arm per combination | Compiler flags every unhandled case | Long `match` for large machines |
| `Result` from transitions | Invalid commands are visible | More types to define and handle |
Common mistakes
- Putting the guarded arm after the general one. The general arm matches first, so the guard never runs. The compiler may warn about an unreachable pattern only when patterns fully overlap. A guarded arm is never considered to cover its pattern, so this mistake often gives no warning.
- Cloning to avoid moves. If you find yourself calling
.clone()on aStringjust to build the next state, check whether takingselfby value would let you move it instead. - Adding flag fields back into variants. A
Connected { session_id: u64, is_valid: bool }brings the original problem back. Ifis_validchanges which operations are allowed, it should be a separate variant. - Using one giant command enum for unrelated machines. Each state machine should have its own command type, so the tuple match stays small.
Exercise
Extend the Door example with a DoorCmd::Break command. A door that is Open, Closed, or Locked becomes a new variant Door::Broken. A broken door refuses every command with a new error DoorError::Broken. Which arms do you add, and where must the Broken arm go relative to the final (door, _) => Ok(door) arm?
Show answer
Add Broken to the Door enum and to DoorError. Add (_, DoorCmd::Break) => Ok(Door::Broken) to make every state break. Add (door @ Door::Broken, _) => Err((door, DoorError::Broken)) to refuse every command on a broken door. Both arms must come before (door, _) => Ok(door), which would otherwise swallow them. The Break arm must also come before the Broken arm so a broken door can still be reported as broken again, or after it if you want Break on a broken door to be an error. Place the Broken arm first if broken doors should refuse even Break.