Sub topic 6
The typestate pattern: making states into types
This chapter assumes you know ownership and moves, generic structs with trait bounds, and impl blocks. It also assumes you have met PhantomData and marker types in the earlier chapters.
The problem: states checked at runtime
Many values have a lifecycle. A door is open or closed. A connection is disconnected, connected, or authenticated. The usual approach stores the state in a field and checks it inside each method:
#[derive(Debug, PartialEq, Clone, Copy)]
enum DoorState {
Open,
Closed,
}
struct Door {
state: DoorState,
}
impl Door {
fn close(&mut self) -> Result<(), String> {
if self.state == DoorState::Closed {
return Err("door is already closed".to_string());
}
self.state = DoorState::Closed;
Ok(())
}
}
fn main() {
let mut door = Door { state: DoorState::Open };
println!("{:?}", door.close());
println!("{:?}", door.close());
}The program compiles. The second close call fails only when it runs, and only if a test or a user triggers that path. The compiler cannot see the mistake, because Door is the same type in every state.
The idea: one type per state
The typestate pattern moves the state out of a field and into the type. A door that is open has type Door<Open>. A door that is closed has type Door<Closed>. These are different types, so the compiler can treat them differently.
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
_state: PhantomData<State>,
}
impl Door<Open> {
fn close(self) -> Door<Closed> {
Door { _state: PhantomData }
}
}
fn main() {
let door: Door<Open> = Door { _state: PhantomData };
let door = door.close();
// door.close(); // error: no method named `close` found for struct `Door<Closed>`
let _ = door;
}Open and Closed are zero-sized marker types. PhantomData<State> lets Door mention the State parameter without storing a value of that type. The tag costs no memory at runtime.
The close method lives in impl Door<Open>. A Door<Closed> has no such method, so calling it is a compile error, not a runtime error.
What the pattern gives you
Three rules produce the behavior:
- State is a type parameter. Each state is a marker type used as the generic argument.
- Methods are tied to states. A method that is valid only in one state goes in an
implblock for that state. The next chapter covers these blocks. - Transitions take
selfby value. A transition consumes the old value and returns one with a new state type. Afterdoor.close(), the oldOpenbinding has been moved and cannot be used. A later chapter covers this.
The diagram shows the legal moves. In a typestate API, the compiler rejects every call that has no arrow.
Where the check moves
| Question | Runtime enum | Typestate |
|---|---|---|
| Where is the state stored? | A field | The type |
| When is a bad call caught? | When the code runs | When the code compiles |
| Failure shape | `Result` or panic | Compile error |
| State known only at runtime? | Works naturally | Needs extra work |
The last row matters. Typestate works when the code path decides the state. If a state comes from user input or a file, the compiler cannot know it, and you must branch on the value yourself. A later chapter compares the two approaches.
Common errors
- Forgetting that transitions consume. If a transition takes
&mut self, it cannot change the type, so a state change needsselfby value. - Reusing a moved binding. After
let door = door.open();the originaldooris gone. Shadowing the name, as the examples do, keeps the code readable. - Making fields public. If outside code can build
Door<Closed>with a struct literal, it can skip the transitions and claim any state. Keep the fields private and expose constructors.
Exercise
A Connection<Disconnected> should be able to call connect(self), which gives a Connection<Connected>. Which impl block should hold connect, and what happens if code calls connect on a Connection<Connected>?
Show answer
Put connect in impl Connection<Disconnected>. Calling it on a Connection<Connected> fails to compile with "no method named connect found", because that impl block applies only to the Disconnected state.