Sub topic 14
Modeling states and commands with enums
This chapter assumes you know how to define enums with data, write match expressions, and add methods with impl. It also assumes you understand moves and borrows.
Why model state with an enum
A connection can be idle, connecting, connected, or failed. A common first attempt is a struct of flags:
struct Connection {
connected: bool,
failed: bool,
session: Option<String>,
attempts: u32,
}This struct can describe nonsense. It can be connected and failed at once, or have a session while not connected. Every function that uses it must guard against those combinations.
An enum lists only the valid states, and each variant carries only the data that state needs. A session string exists only in Connected. An attempt counter exists only in Connecting. The invalid combinations cannot be written.
Commands as a second enum
Events that change the state can also be an enum. Each variant is one kind of command, with its payload. The state's next method takes the current state and a command, then returns the new state.
#[derive(Debug)]
enum State {
Idle,
Connecting { attempts: u32 },
Connected { session: String },
Failed(String),
}
enum Command {
Connect,
Succeed(String),
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::Succeed(session)) => {
State::Connected { session }
}
(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::Succeed("abc".to_string()),
Command::Disconnect,
];
for cmd in commands {
state = state.next(cmd);
println!("{:?}", state);
}
}The program prints Connecting { attempts: 1 }, Connecting { attempts: 2 }, Connected { session: "abc" }, and Idle.
How the pieces work
- Matching a tuple.
match (self, cmd)tests both values at once, so each arm names one valid transition. - Taking
selfby value. The old state is consumed. Arms can move data such as thesessionstring into the new state without cloning, and nobody can keep using a stale state. - Guards.
if attempts < 3separates a retry from the final failure. The guarded arm comes first, and the next arm handles the remainingFailcase. - Reassignment. The caller writes
state = state.next(cmd), so one variable always holds the current state.
The catch-all trade-off
The last arm, (state, _) => state, ignores commands that do not apply, such as Disconnect while Idle. It also turns off exhaustiveness checking for this match. If you add a Paused state later, the compiler will not point you to this function.
If you want the compiler to flag new variants, list the ignored pairs explicitly, or make invalid commands return a Result.
Exercise
In the code above, what happens if Command::Fail arrives while the state is Connecting { attempts: 3 }, and why does the guarded arm not match?
Show answer
The guard attempts < 3 is false, so the guarded arm is skipped. The next arm matches (State::Connecting { .. }, Command::Fail(reason)) and returns State::Failed(reason).