Sub topic 6
The typestate pattern: making states into types
This chapter assumes you know Rust ownership and moves, structs and impl blocks, generic type parameters, and how to read compiler errors. It also assumes you have seen PhantomData<T> and zero-sized marker types from the earlier chapters. Here they are the building blocks, and the question is what to build with them.
The problem: states that only exist in your head
Many objects have a lifecycle. A network session is disconnected, then connected, then disconnected again. A file is open or closed. An HTTP request is being built, then sent. Some operations make sense only in some states. You can't send data on a session that isn't connected.
The usual way to model this is a field that records the current state. The program checks the field at runtime:
#[derive(Debug, PartialEq)]
enum Status {
Disconnected,
Connected,
}
struct Session {
host: String,
status: Status,
}
impl Session {
fn new(host: &str) -> Self {
Session { host: host.to_string(), status: Status::Disconnected }
}
fn connect(&mut self) -> Result<(), String> {
if self.status == Status::Connected {
return Err("already connected".to_string());
}
self.status = Status::Connected;
Ok(())
}
fn send(&self, msg: &str) -> Result<(), String> {
if self.status != Status::Connected {
return Err("not connected".to_string());
}
println!("to {}: {}", self.host, msg);
Ok(())
}
}
fn main() {
let mut session = Session::new("example.com");
match session.send("hello") {
Ok(()) => println!("sent"),
Err(e) => println!("error: {e}"),
}
session.connect().unwrap();
session.send("hello").unwrap();
}This code is correct, and the first send call fails at runtime as designed. But the mistake of sending before connecting compiles without complaint. Every method must remember to check status. Every caller must handle a Result for a situation that is a programming error, not a runtime condition like a dropped network link. The rules of the lifecycle are written nowhere the compiler can read.
The idea: put the state in the type
The typestate pattern moves the state out of a field and into the type. Instead of one Session type with a status value, you have Session<Disconnected> and Session<Connected>. These are different types. The compiler already knows how to stop you from calling a method on the wrong type, so it can now stop you from calling send in the wrong state.
Three pieces make this work:
- Marker types represent the states. They are empty structs such as
struct Connected;. They hold no data, and their only job is to be a name the type system can see. - A generic parameter on the main struct says which state a value is in.
PhantomData<S>lets the struct mentionSwithout storing one. - Methods that take
selfby value perform transitions. A method likeconnectconsumes aSession<Disconnected>and returns aSession<Connected>.
Here is the same session written this way:
use std::marker::PhantomData;
struct Disconnected;
struct Connected;
struct Session<S> {
host: String,
_state: PhantomData<S>,
}
impl Session<Disconnected> {
fn new(host: &str) -> Self {
Session { host: host.to_string(), _state: PhantomData }
}
fn connect(self) -> Session<Connected> {
Session { host: self.host, _state: PhantomData }
}
}
impl Session<Connected> {
fn send(&self, msg: &str) {
println!("to {}: {}", self.host, msg);
}
fn disconnect(self) -> Session<Disconnected> {
Session { host: self.host, _state: PhantomData }
}
}
fn main() {
let session = Session::new("example.com");
// session.send("too early"); // does not compile, see below
let session = session.connect();
session.send("hello");
let session = session.disconnect();
let _ = session;
}There is no status field, no Result, and no runtime check. send is defined only on Session<Connected>, so it does not exist on a Session<Disconnected>. If you uncomment the early call, the compiler stops you:
error[E0599]: no method named `send` found for struct `Session<Disconnected>` in the current scopeThe error is reported at build time, on the exact line, and the program never runs with the bug. The next two chapters cover the mechanics of writing state-specific impl blocks and transitions in detail. This chapter focuses on why the structure works.
How the compiler sees it
Each concrete choice of S produces a separate type. Session<Disconnected> and Session<Connected> have the same fields and the same memory layout, because PhantomData<S> and the marker types are zero-sized. At runtime they are indistinguishable. At compile time they are unrelated types, and each has its own set of inherent methods.
You can think of the pattern as a state machine drawn in the type system:
Notice the difference between the two kinds of arrow. A transition such as connect(self) changes the type. An operation such as send(&self) stays in the same state, so it borrows and leaves the type unchanged.
Why consuming `self` matters
Transitions take self by value, not &mut self. This is what stops you from keeping a stale handle. After connect, the old Session<Disconnected> has been moved, so ownership rules forbid using it:
use std::marker::PhantomData;
struct Disconnected;
struct Connected;
struct Session<S> {
host: String,
_state: PhantomData<S>,
}
impl Session<Disconnected> {
fn new(host: &str) -> Self {
Session { host: host.to_string(), _state: PhantomData }
}
fn connect(self) -> Session<Connected> {
Session { host: self.host, _state: PhantomData }
}
}
fn main() {
let idle = Session::new("example.com");
let live = idle.connect();
// let again = idle.connect(); // error[E0382]: use of moved value: `idle`
let _ = live;
}Without the move, you could write a function that changes a session's state and still hold a reference typed as the old state. Taking self by value makes the type of every binding match the real state of the object. Rust's ownership system does the bookkeeping that a state field did in the runtime version.
What typestate buys you, and what it costs
| Property | Runtime state field | Typestate |
|---|---|---|
| Invalid call order detected | When the code runs | When the code compiles |
| Cost per check | A branch on each call | None |
| Extra memory for state | One field | None, because markers are zero-sized |
| Method signatures | Often return `Result` | Return the value directly |
| State decided by | Runtime data (a file, user input, network) | Code structure only |
| Error messages | Your own strings | Compiler errors, which can be cryptic |
The last-but-one row is the main limit. The type of a value is fixed when the code is compiled. If the next state depends on something only known at runtime, such as whether a connection attempt succeeded, a single transition cannot return one fixed type. You have to return an enum, or a Result whose Ok and Err variants carry different state types. The pattern still works there, but the types get larger. The trade-offs chapter returns to this.
Designing the states
A few rules help when you decide what to turn into a type.
- Use a state for each phase where the set of valid operations differs. If
sendis valid in two phases andclosein a third, those are likely three states. If two phases allow identical operations, merge them. - Keep data that all states share in the struct, and data that only one state has in the marker or a state-specific field. In the examples above,
hostlives in every state, so it stays inSession. Data that exists only after connecting could be stored in the state type itself, for exampleConnected { id: u64 }, but that makes the state non-zero-sized. - Name states as nouns or adjectives that describe the object now, such as
ConnectedorOpen. Names likeAfterConnectdescribe history and read badly in type signatures. - Give users a way to name the types. If a function should accept only connected sessions, it can say
fn run(s: Session<Connected>). If it should accept any state, it can be generic:fn log<S>(s: &Session<S>).
Common mistakes
- Using
&mut selffor a transition. A&mut selfmethod cannot change the type of the value it borrows, so it cannot move aSession<Disconnected>into aSession<Connected>. Transitions must takeselfand return a new value. - Forgetting that fields must be moved out. In
connect,host: self.hostmoves theStringinto the new value. If you also want to keep usingselfafterward, you have designed a clone, not a transition. - Expecting runtime branching to work on the type. You cannot write
if condition { session.connect() } else { session }and get one type from both branches, because the branches have different types and theifmust produce one. Use an enum or separate code paths. - Putting too many type parameters on one struct. Each independent dimension of state multiplies the number of
implblocks. Two parameters with three states each give nine combinations. If that happens, check whether you are modelling too much at the type level.
Where the pattern shows up
Typestate appears in embedded Rust, where a pin must be configured as an input or output before use, and in protocol clients that must authenticate before issuing commands. It appears in builders that refuse to build until required fields are set. The next chapters develop these uses in turn. All of them rely on the three parts you saw here: marker types, a generic state parameter, and transitions that consume self.
Exercise
A colleague writes a transition as fn connect(&mut self) -> Session<Connected> on impl Session<Disconnected>, building the new value from self.host.clone(). The code compiles. Why does this weaken the typestate guarantee, and how do you fix it?
Show answer
Because connect only borrows the session, the original Session<Disconnected> is still alive and usable after the call. The caller holds both a disconnected and a connected session for the same logical connection, so the type of a binding no longer tells you the real state. The fix is to take self by value and move host into the new Session<Connected>. The old binding is then moved and cannot be used again.
Exercise
Why can the typestate version of Session avoid returning Result from send, while the runtime version cannot?
Show answer
In the typestate version, send exists only on Session<Connected>, so calling it in the wrong state is a compile error and never happens at runtime. There is no failure to report. The runtime version must handle a call made in the wrong state, so it returns a Result to signal that failure. Other failures, such as a broken network link, would still need a Result in both versions.