Sub topic 13
When typestate helps and when it does not
This chapter assumes you have read the earlier chapters on PhantomData, marker types, state-specific impl blocks, consuming transitions and sealed state traits. You should be comfortable with enums, Result, and moving values in Rust.
Typestate turns some mistakes into compile errors. It also adds type parameters, more impl blocks, and restrictions on how values can be stored and passed around. This chapter gives you criteria for deciding when that exchange is worth making.
What typestate buys you
Typestate moves the check for "is this call valid right now?" from run time to compile time. That gives you three concrete benefits.
- No runtime check and no error path. A method that exists only on
Door<Open>needs noResultfor "wrong state". Callers never write handling code for a case that cannot happen. - Documentation the compiler enforces. The method list for
Door<Closed>in rustdoc shows what you can do in that state. - No runtime cost. Marker types are zero-sized, so
Door<Open>andDoor<Closed>have the same layout as a plain struct with the same fields.
Compare this with the runtime version of the same door:
#[derive(Debug, Clone, Copy, PartialEq)]
enum DoorState {
Open,
Closed,
}
#[derive(Debug)]
struct WrongState(DoorState);
struct Door {
state: DoorState,
}
impl Door {
fn new() -> Self {
Door { state: DoorState::Closed }
}
fn open(&mut self) -> Result<(), WrongState> {
match self.state {
DoorState::Closed => {
self.state = DoorState::Open;
Ok(())
}
other => Err(WrongState(other)),
}
}
fn close(&mut self) -> Result<(), WrongState> {
match self.state {
DoorState::Open => {
self.state = DoorState::Closed;
Ok(())
}
other => Err(WrongState(other)),
}
}
}
fn main() {
let mut door = Door::new();
door.open().unwrap();
println!("{:?}", door.close());
println!("{:?}", door.close());
}This version compiles, and the second close fails only when the program runs. It is also easy to store in a Vec, change through a &mut reference, and read from a config file. The typestate version cannot do all of that without extra work.
Where typestate fits well
The pattern works best when most of the following are true.
- The state sequence is known when you write the code. A connection that must be configured, then connected, then authenticated follows a fixed script.
- A wrong call is costly. Sending data on a closed socket, committing a finished transaction, or building a request with no URL are bugs you want to catch before the program runs.
- The API is used by many callers. A library with many users gets more value from compile-time errors than a short script with one caller.
- Values move through states in a line. A value that is created, transformed and consumed fits the by-value transitions well.
- The number of states and independent flags is small. Two to five states is comfortable.
Well-known examples include builders with required fields, protocol handshakes, file or transaction handles that are consumed on commit, and hardware pin configuration in embedded code. In embedded code a pin type such as Pin<Output> or Pin<Input> prevents you from reading an output-only pin.
Where typestate gets in the way
The state is only known at run time
If the state comes from outside the program, such as a file, a network message or user input, the compiler cannot know it. You have to convert a runtime value into a typed value somewhere, and that conversion is a runtime check anyway. A typical bridge is an enum that holds each typed state:
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<S> {
name: String,
_state: PhantomData<S>,
}
impl Door<Closed> {
fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
fn open(self) -> Door<Open> {
Door { name: self.name, _state: PhantomData }
}
}
impl Door<Open> {
fn close(self) -> Door<Closed> {
Door { name: self.name, _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 is_open(&self) -> bool {
matches!(self, AnyDoor::Open(_))
}
}
fn main() {
let doors = vec![
AnyDoor::Closed(Door::new("front")),
AnyDoor::Closed(Door::new("back")),
];
let doors: Vec<AnyDoor> = doors.into_iter().map(AnyDoor::toggle).collect();
for d in &doors {
println!("open: {}", d.is_open());
}
}Vec<Door<Open>> and Vec<Door<Closed>> are different types, so a collection of mixed states needs this wrapper. Once you write AnyDoor, you have a runtime state enum again. Inside each match arm you still get typed access, but at the edges you are back to dynamic dispatch on state. If a large share of your code lives behind AnyDoor, typestate is giving you less than it appeared to.
Transitions can fail
A consuming transition takes ownership. If it can fail, a plain Result<Door<Open>, Error> loses the original door, because it was moved in. Return the old state in the error so the caller can retry:
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<S> {
locked: bool,
_state: PhantomData<S>,
}
impl Door<Closed> {
fn new(locked: bool) -> Self {
Door { locked, _state: PhantomData }
}
fn try_open(self) -> Result<Door<Open>, Door<Closed>> {
if self.locked {
Err(self)
} else {
Ok(Door { locked: false, _state: PhantomData })
}
}
fn unlock(mut self) -> Self {
self.locked = false;
self
}
}
fn main() {
let door = Door::<Closed>::new(true);
let door = match door.try_open() {
Ok(_open) => unreachable!("the door was locked"),
Err(closed) => closed.unlock(),
};
match door.try_open() {
Ok(_) => println!("opened"),
Err(_) => println!("still closed"),
}
}This works, but every fallible transition now has a more complicated signature. Types like Result<Door<Open>, (Door<Closed>, Error)> are common in real typestate APIs, and callers have to learn them.
Mutation through references
Transitions take self by value. If your value lives behind &mut, inside a struct field, or in a collection, you cannot move out of it without a replacement. The usual workarounds are Option::take, std::mem::replace with a placeholder, or keeping the typed value in an Option field. All of them add noise and a runtime None case, which is the kind of check you were trying to avoid.
Drop and moving fields out
Rust does not allow a Drop implementation for only one instantiation. You cannot write impl Drop for Door<Open>, and the compiler rejects it. A Drop implementation must be generic over every state, so it has to cover all of them. A type that implements Drop also cannot have its fields moved out, so transitions that destructure self stop working. You can still rebuild the value with std::mem::take or Option fields, or put the Drop logic in a small inner field type instead.
Combinatorial growth
One state parameter is easy. Several independent parameters multiply:
- A builder with three optional-then-required fields has 2³ = 8 type combinations.
- Each combination may need its own
implor a clever blanketimpl. - Signatures such as
Client<Configured, Unauthenticated, Tls>appear in error messages and in every function that accepts the type.
If you reach this point, check whether some parameters can become ordinary runtime fields, or whether a split into separate types would be clearer.
Error messages and API cost
When someone calls a method that does not exist in the current state, the compiler reports no method named close found for struct Door<Closed>. That is clear to a reader who knows the pattern. Expect more confusion when the failure comes from a missing trait bound deep in a generic function.
The states also become part of your public API. Adding a new state is a breaking change for anyone who wrote a match over your wrapper enum or who named the state types in signatures. A sealed trait helps keep outside code from implementing new states, but it does not stop callers from naming them.
Each distinct state also produces its own monomorphized copy of generic code. For a handful of states this is negligible, but it grows with the number of combinations.
A decision guide
The flowchart summarizes the questions to ask in order.
The table compares the approaches on the points that usually decide the choice.
| Concern | Typestate | State enum in one struct | Runtime flag with checks |
|---|---|---|---|
| Invalid call detected | Compile time | Run time, via `match` | Run time, via `if` |
| Needs a `Result` for wrong state | No | Usually yes | Usually yes |
| State chosen from input data | Needs a wrapper enum | Natural fit | Natural fit |
| Store mixed states in a `Vec` | Needs a wrapper enum | Natural fit | Natural fit |
| Mutate through `&mut` | Awkward | Natural fit | Natural fit |
| Many independent flags | Type explosion | Manageable | Manageable |
| Per-state data | Strong, only in that state | Possible with enum variants | Weak, fields always present |
| Runtime overhead | None | A tag and a branch | A flag and a branch |
An enum with data in each variant is often the middle path. If the main goal is to avoid reading fields that do not apply in a state, a enum Connection { Idle, Active { socket: TcpStream } } gives you that without any type parameters. It still checks the state at run time, but it makes illegal field combinations unrepresentable.
Practical advice
- Start with the simplest design. Write the enum or flag version first. Move to typestate when you see a real bug class that it would remove, or when the API is public and misuse is expensive.
- Use typestate for the part that is linear. A builder is a good example, because it is created, filled in and consumed once. A long-lived object that changes state many times is a weaker fit.
- Keep the number of state parameters low. One parameter is easy to read. Two is manageable. Three or more should make you reconsider.
- Test the rejected paths. Use
compile_faildoctests, as covered in the previous chapter, so a refactor does not quietly make an invalid call compile. - Provide a runtime escape hatch where needed. A wrapper enum such as
AnyDoorcosts little and lets callers who only know the state at run time still use your types.
Exercise
A service reads a "connection mode" value from a config file and then must call different methods depending on it. Would you model the mode as a typestate parameter? Explain what you would do instead or in addition.
Show answer
A pure typestate parameter does not fit, because the mode is only known at run time and the compiler cannot choose a type from a file value. Parse the value into an enum at the edge of the program, then match on it once. Inside each match arm you can still call typed APIs such as Connection<Secure> or Connection<Plain>, or wrap them in a small enum like AnyConnection. The runtime check happens once, at the boundary, and the rest of the code gets compile-time guarantees.
Exercise
You have a consuming method fn commit(self) -> Result<Committed, CommitError> on Transaction<Active>. When commit fails because of a temporary network error, the caller wants to retry. What is wrong with this signature, and how would you fix it?
Show answer
The method takes self by value, so on failure the transaction has already been moved and the caller cannot retry. Return the original value in the error case, for example Result<Transaction<Committed>, (Transaction<Active>, CommitError)>, or put it inside CommitError. The caller then gets the active transaction back and can call commit again or roll back.
Exercise
A builder has four independent optional features, each of which must be marked "on" or "off" at the type level so that dependent methods are available. Roughly how many distinct builder types does this create, and what would you consider doing about it?
Show answer
Four independent two-valued flags give 2^4 = 16 distinct types. That is hard to read in signatures and error messages and may require many impl blocks. Keep type-level flags only for the features that gate real methods or required fields, and turn the rest into ordinary runtime fields with defaults. If several flags always change together, merge them into one state type.