Typestate
Typestate encodes an object's stage of life in a generic parameter so illegal calls do not compile. A Connection<Closed> has no read method.
Detailed Explanation
A boolean connected plus a read that panics when false is a runtime check. Typestate makes the check a type. struct Connection<S> { ... phantom: PhantomData<S> } with struct Closed; struct Open;. impl Connection<Closed> { fn open(self) -> Connection<Open> { ... } }. impl Connection<Open> { fn read(&mut self) -> ... { ... } fn close(self) -> Connection<Closed> { ... } }. There is no read on Closed. The compiler is the state machine.
self by value on transitions is common: you consume the closed connection and return an open one, so the old value cannot be used. If the transition can fail, return Result<Connection<Open>, (Connection<Closed>, Error)> so the caller still has the closed value.
The state types are unit structs. They disappear at runtime (PhantomData). You are not storing an enum of states unless you also need to pick the state dynamically. A runtime state enum plus match is the other design; typestate is for sequences you can prove in the types (builder completeness, handshake protocols, file open/close).
The cost is API surface: many impl blocks, and generics leaking into signatures. A public typestate API is a compatibility commitment — adding a state is a new type. Keep typestate at the edges that hurt when misused, not on every internal struct.
When you reach for typestate: builders with required fields, protocols, resource open/close. When you reach for an enum: the state is chosen at runtime and you will match. When you reach for a boolean: one flag and a private method you control.
Code Examples
use std::marker::PhantomData;
struct Closed;
struct Open;
struct Conn<S> {
_s: PhantomData<S>,
}
impl Conn<Closed> {
fn new() -> Self {
Self { _s: PhantomData }
}
fn open(self) -> Conn<Open> {
Conn { _s: PhantomData }
}
}
impl Conn<Open> {
fn read(&self) -> &'static str {
"ok"
}
}
fn main() {
let c = Conn::new().open();
println!("{}", c.read()); // prints: ok
// Conn::new().read(); // does not compile
}Common Gotchas
Transitions should take `self` by value
Leaving a `Connection<Closed>` around after `open` is a stale handle. Consume it.
Failed transitions must return the old value
If `open` takes `self` and returns `Err` without it, the connection is gone. Return `(Self, Error)`.
`PhantomData<S>` marks the state
Without it a `Conn<S>` with no `S` field may trigger unused-parameter errors and dropck surprises.
Do not typestate an internal type that changes every week
The compile-time safety is not worth the impl noise. Use an enum.