Sub topic 13
When typestate helps and when it does not
This chapter assumes you have read the earlier chapters. You should know PhantomData, marker types, state-specific impl blocks, and transitions that consume self. Typestate is a tool with a price, so this chapter gives you criteria for deciding when to pay it.
What typestate buys you
Typestate moves a class of mistakes from runtime to compile time. It works best under these conditions:
- The valid call order is fixed and known when you write the code.
- Misuse is costly. Examples are sending data on a closed connection, or building a request without its URL.
- The API is used by many callers you cannot review, such as a library's users.
- Each state exposes different methods, so the type documents what you can do next.
Embedded hardware drivers are a common case. A pin is configured as input or output, and writing to an input pin is a bug that should never ship.
What typestate costs
- Error messages. A missing method on
Door<Closed>is clear. Long chains of generic parameters produce harder messages. - Type signatures. Every function that accepts a door must name its state or be generic over it.
- Runtime-chosen states. The compiler must know the state statically. If a config file or network message decides the state, one variable cannot hold "some state".
- Heterogeneous collections.
Vec<Door<?>>has no single element type. - Combinatorial growth. A builder with several required fields needs one type parameter per field, and transitions multiply.
- Moved values. Transitions consume
self, so you cannot transition through a&mutreference without extra work.
The runtime alternative
An enum checks the state at runtime and reports misuse as a Result.
#[derive(Debug)]
enum DoorError {
AlreadyClosed,
}
enum Door {
Open,
Closed,
}
impl Door {
fn close(&mut self) -> Result<(), DoorError> {
match self {
Door::Open => {
*self = Door::Closed;
Ok(())
}
Door::Closed => Err(DoorError::AlreadyClosed),
}
}
}
fn main() {
let mut door = Door::Open;
println!("{:?}", door.close());
println!("{:?}", door.close());
}This prints Ok(()) and then Err(AlreadyClosed). The second call compiles, and the failure shows up at runtime. In exchange, the door can sit in a Vec, work through &mut, and take its state from data.
Bridging the two with an enum wrapper
When some code needs the static guarantees and other code needs dynamic state, wrap the typed versions in an enum. Match on it once at the boundary.
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<S> {
_state: PhantomData<S>,
}
impl Door<Closed> {
fn new() -> Self {
Door { _state: PhantomData }
}
fn open(self) -> Door<Open> {
Door { _state: PhantomData }
}
}
impl Door<Open> {
fn close(self) -> Door<Closed> {
Door { _state: PhantomData }
}
}
enum AnyDoor {
Open(Door<Open>),
Closed(Door<Closed>),
}
impl AnyDoor {
fn toggle(self) -> AnyDoor {
match self {
AnyDoor::Open(d) => AnyDoor::Closed(d.close()),
AnyDoor::Closed(d) => AnyDoor::Open(d.open()),
}
}
}
fn main() {
let doors = vec![AnyDoor::Closed(Door::new()), AnyDoor::Closed(Door::new())];
let doors: Vec<AnyDoor> = doors.into_iter().map(AnyDoor::toggle).collect();
let open = doors.iter().filter(|d| matches!(d, AnyDoor::Open(_))).count();
println!("{} doors open", open);
}Inside toggle, each arm still gets compile-time checking. The enum only restores the runtime variety that a collection needs.
Deciding
Summary of the trade-off
| Concern | Typestate | Enum with runtime checks |
|---|---|---|
| Invalid order | Compile error | `Err` or panic at runtime |
| State from data | Needs an enum wrapper | Natural |
| Collections of mixed states | Needs an enum wrapper | Natural |
| Signature noise | Higher | Low |
| Mutation through `&mut` | Awkward | Natural |
Exercise
A network client reads a "mode" field from a config file at startup. The mode is either "read-only" or "read-write", and each mode exposes different methods. Would you model the mode with typestate alone? Explain.
Show answer
No. The mode is known only at runtime, so a single variable cannot have type Client<ReadOnly> or Client<ReadWrite> depending on the file. Use typestate for the two client types, then wrap them in an enum such as AnyClient and match once after reading the config. Code that needs one specific mode takes the typed client. Code that handles either mode takes the enum.
Exercise
Give two reasons to prefer an enum with a Result-returning method over typestate for a connection pool that stores connections in a Vec.
Show answer
First, a Vec needs one element type, and typestate gives each state its own type. Second, pool code usually changes a connection's state through &mut, while typestate transitions consume self. An enum handles both directly.