Runtime States and Typestate in Rust


In this post

An order enters the system as a draft, gets validated, and eventually executes. Each stage allows different operations: a draft can be edited but not executed, a validated order can be executed but not edited. A state machineIn theoretical computer science, a finite-state machine (FSM) or finite-state automaton, finite automaton, or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number of states at any given time. The FSM can change from one state to another in response to some inputs; the change from one state to another is called a transition. An FSM is defined by a list of its states, its initial state, and the inputs that trigger each transition. Finite-state machines are of two types—deterministic finite-state machines and non-deterministic finite-state machines. For any non-deterministic finite-state machine, an equivalent deterministic one can be constructed.Read on Wikipedia → is a value that is always in exactly one of a known set of states, where each state allows its own operations and transitions, and an order is a small one.

Rust can enforce that lifecycle in two different places. One design keeps all states inside a single value, as an enum, and rejects wrong transitions while the program runs. The other gives each state its own type, so that calling an operation in the wrong stage fails to compile. The earlier post on modeling data with Rust’s type system introduced both ideas in brief; this post builds the same order lifecycle in both styles and compares what each one guarantees, what each one costs, and what the compiler reports when the code gets it wrong.

The same lifecycle in two places

The natural starting point is one struct with a status field:

struct Order {
    id: u64,
    status: Status, // Draft, Validated, or Executed
    lines: Vec<Line>,
    execution: Option<Execution>, // present only when status is Executed
}

This compiles, and nothing in the type stops an Order from carrying an execution while its status is still Draft. (Status here is an enum of bare tags, with no data attached.) The rule lives in a comment, and every function that touches the struct has to re-check it.

The two designs that fix this move the rule into different places. The runtime design makes an invalid combination impossible to construct: the enum variant for “draft” simply has no execution field, so there is no place to store it. The compile-time design makes an invalid operation impossible to call: the method execute exists only on the validated state’s type, so there is no way to invoke it on a draft.

The choice follows one question: whether an event at runtime or the code path chooses the next state. A user clicking “execute”, a network reply, a timer — these are events, and the program must inspect the current value and branch. A builder that must be configured before it is built, a handshake that must complete before messages flow — these sequences are fixed by the code itself, and the compiler can check them.

A state machine that runs

The runtime version keeps the states as enum variants, and each variant carries the data that its stage needs. A draft has lines that can still be edited. An executed order has the execution record instead:

struct Line {
    quantity: u64,
}

struct Execution {
    price: u64,
    quantity: u64,
}

enum OrderState {
    Draft { lines: Vec<Line> },
    Validated { lines: Vec<Line> },
    Executed { execution: Execution },
}

There is no Option<Execution> waiting for a later stage. A draft cannot hold execution data because its variant has no field for it.

Transitions are functions from one state to another. Events come in from outside, and each combination of current state and event either produces the next state or explains why it is rejected:

#[derive(Debug)]
enum Event {
    Validate,
    Execute { price: u64 },
}

#[derive(Debug)]
enum TransitionError {
    EmptyLine,
    UnexpectedEvent { state: &'static str, event: Event },
}

fn transition(state: OrderState, event: Event) -> Result<OrderState, TransitionError> {
    match state {
        OrderState::Draft { lines } => match event {
            Event::Validate => {
                if lines.iter().any(|line| line.quantity == 0) {
                    return Err(TransitionError::EmptyLine);
                }
                Ok(OrderState::Validated { lines })
            }
            other => Err(TransitionError::UnexpectedEvent {
                state: "draft",
                event: other,
            }),
        },
        OrderState::Validated { lines } => match event {
            Event::Execute { price } => {
                let quantity: u64 = lines.iter().map(|line| line.quantity).sum();
                Ok(OrderState::Executed {
                    execution: Execution { price, quantity },
                })
            }
            other => Err(TransitionError::UnexpectedEvent {
                state: "validated",
                event: other,
            }),
        },
        OrderState::Executed { .. } => Err(TransitionError::UnexpectedEvent {
            state: "executed",
            event: event,
        }),
    }
}

An Execute event arriving while the order is still a draft reaches the catch-all arm and comes back as an error:

let state = OrderState::Draft { lines: vec![Line { quantity: 3 }] };

match transition(state, Event::Execute { price: 100 }) {
    Ok(_) => {} // an execute event never moves a draft, so this arm stays empty here
    Err(TransitionError::UnexpectedEvent { state, .. }) => {
        println!("rejected while {}", state); // rejected while draft
    }
    Err(error) => println!("invalid order: {error:?}"),
}

The rejection happens when the program runs, and the caller handles it like any other error. That is the design’s defining property, and it splits into two promises. The compiler does guarantee that every state is handled: the match covers all variants, so adding a Cancelled variant later breaks every transition function until its arms are written. The compiler does not guarantee that any transition is valid — “executing a draft is wrong” is a rule the runtime check enforces, one call at a time.

In exchange, the value works everywhere a value can go. A Vec<OrderState> holds drafts next to executed orders directly, and an order saved to a database deserializes back into the same enum with its variant as the tag. The standard library follows this shape when the state arrives from outside: std::collections::hash_map::Entry is an enum with Occupied and Vacant variants that the caller matches on, because whether a key exists is something the program discovers at runtime, not something the code fixed in advance.

A state machine that compiles

The same lifecycle can instead become three types. The order keeps one struct, and the state becomes a type parameter carried by a marker:

use std::marker::PhantomData;

pub struct Draft;
pub struct Validated;
pub struct Executed;

pub struct Order<State> {
    lines: Vec<Line>,
    _state: PhantomData<State>,
}

Draft, Validated, and Executed are unit structs: types with no data, whose only job is to be named. PhantomData<State> lets the struct carry that name without storing anything for it — Order<Draft> occupies exactly the memory of its payload fields, so the marker costs nothing at runtime. The type-system post introduced this marker and its role in how the compiler treats ownership; here the question is what the pattern does for the lifecycle as a whole.

Operations attach to the state they belong to. Each impl block names its state, so its methods exist only for values in that state:

#[derive(Debug)]
pub struct NotValidated;

impl Order<Draft> {
    pub fn new(lines: Vec<Line>) -> Self {
        Order { lines, _state: PhantomData }
    }

    pub fn validate(self) -> Result<Order<Validated>, (Self, NotValidated)> {
        if self.lines.iter().any(|line| line.quantity == 0) {
            return Err((self, NotValidated));
        }
        Ok(Order { lines: self.lines, _state: PhantomData })
    }
}

impl Order<Validated> {
    pub fn execute(self) -> Order<Executed> {
        Order { lines: self.lines, _state: PhantomData }
    }
}

Operations that make sense in every state go in one generic block:

impl<State> Order<State> {
    pub fn total(&self) -> u64 {
        self.lines.iter().map(|line| line.quantity).sum()
    }
}

With this shape, validate takes self by value and consumes the draft. After the call, the Order<Draft> value no longer exists anywhere:

let draft = Order::<Draft>::new(vec![Line { quantity: 3 }]);
let validated = match draft.validate() {
    Ok(validated) => validated,
    Err(_) => panic!("the example lines are valid"),
};
let executed = validated.execute(); // validated moves into the next state in turn
println!("{}", draft.total()); // does not compile: draft was moved

The compiler reports the reuse:

error[E0382]: borrow of moved value: `draft`
  |
  |     let validated = match draft.validate() {
  |                                 ---------- `draft` moved due to this method call
...
  |     println!("{}", draft.total());
  |                    ^^^^^ value borrowed here after move

An old state cannot be used after its transition, because it is not there to use. Compiler output in this post is abridged to the lines that matter.

Calling an operation from the wrong stage fails earlier, at the method lookup:

let draft = Order::<Draft>::new(vec![Line { quantity: 1 }]);
draft.execute(); // does not compile
error[E0599]: no method named `execute` found for struct `Order<Draft>` in the current scope
   |
   | impl Order<Validated> {
   | --------------------- method `execute` not found for this struct
...
   |     draft.execute();
   |           ^^^^^^^ method not found in `Order<Draft>`
   |
   = note: the method was found for `Order<Validated>`

The message names both the state that received the call and the state that owns the method, so the fix is stated in the error itself. Passing a value to a function that expects one particular state fails the same way, with both states named:

error[E0308]: mismatched types
   |
   |     requires_validated(&draft);
   |     ------------------ ^^^^^^ expected `&Order<Validated>`, found `&Order<Draft>`

Failure needs a signature decision that the enum version never faced. validate returns Result<Order<Validated>, (Self, NotValidated)> — the error payload carries the original Order<Draft> beside the error value, so the caller can inspect the rejected draft and try again instead of losing it:

match draft.validate() {
    Ok(validated) => ship(validated),
    Err((draft, NotValidated)) => fix_lines(draft), // the draft came back
}

(ship and fix_lines stand for the caller’s own next steps.) The alternative signature — Result<Order<Validated>, NotValidated> — is shorter, but a failed validation destroys the draft. Every state that has a failing transition must make this choice, and a five-step protocol with three failure points accumulates three of these payload decisions.

What typestate costs

At runtime, the zero-byte marker is all a typestate value adds. The pattern’s checks are paid for in four places.

Generic spread. Anything that handles an order “in whatever state” needs the state as a type parameter, and that parameter travels into every signature that calls it. A helper open to all states is easy:

fn audit<State>(order: &Order<State>) -> String {
    format!("total {}", order.total())
}

A helper limited to some states needs a trait bound, and the states must declare membership:

trait PreTrade {}
impl PreTrade for Draft {}
impl PreTrade for Validated {}

fn summary<State: PreTrade>(order: &Order<State>) -> u64 {
    order.total()
}

Passing an executed order to summary fails with a message that names both sides: “the trait PreTrade is not implemented for Executed”. Readable, but the reader now tracks a second axis — types and the traits they implement — to know what a function accepts.

Machine code per state. Rust compiles generic code into a specialized copy for each concrete type — monomorphization — which is why total() runs as fast as a hand-written function and why a typestate design with N states produces N copies of every generic helper that touches the state parameter. A runtime enum has one copy of transition and one dispatch at runtime; the typestate version trades that dispatch for compiled duplication.

Failure-path bookkeeping. Shown above: each failing transition settles what its error payload carries, and returning the current state for retry makes signatures longer at every step that can fail.

Storage. A collection must choose one state:

let validated: Order<Validated> = /* ... */;
let book: Vec<Order<Draft>> = vec![validated]; // does not compile
error[E0308]: mismatched types
   |
   |     let book: Vec<Order<Draft>> = vec![validated];
   |                                        ^^^^^^^^^ expected `Order<Draft>`, found `Order<Validated>`

When a system must store orders in mixed states, the mixed collection needs an enum whose variants wrap the typestates:

enum StoredOrder {
    Draft(Order<Draft>),
    Validated(Order<Validated>),
    Executed(Order<Executed>),
}

Storage keeps the wrapper; operations take a typed value out and push the transitioned result back:

if let Some(StoredOrder::Draft(draft)) = book.pop() {
    if let Ok(validated) = draft.validate() {
        book.push(StoredOrder::Validated(validated));
    }
}

The hybrid compiles and runs, and it is a common shape in real systems: the database and the queues hold the enum, the business logic holds the typestate, and the conversion points between them are explicit. Persistence is the same boundary from the other side — a saved order is a tag plus data, and the type parameter exists only while the process holds the value in memory.

Choosing where the state lives

QuestionRuntime enumTypestate
Where the state livesin the valuein the type
Invalid transitionruntime error (Result)does not compile
What the compiler promisesall states handledorder of operations enforced
Mixed collectionone type, directneeds an enum wrapper
Persistenceone tagged typeerased at the storage boundary
Adding a statenew variant, compiler lists missing armsnew marker type and impl blocks
Machine codeone copy, runtime dispatchspecialized copy per state
Failure handlingone error typeper-step signature decisions

The table lists the trade-offs; the guidance follows from them. When the next state is chosen by events the code does not schedule — user input, network replies, failures — the runtime enum is the model, because those decisions happen while the program runs and the error branch is where they belong. When the sequence is fixed by the code’s own control flow, typestate turns “called in the wrong order” into a compile error, and the checks it replaces would otherwise be runtime panics or silent bugs. Builders and protocol handshakes have this shape.

Typestate is also the established design where a value’s state is configured once and then never changes again. Embedded device crates encode a pin’s configured mode — input or output, pull-up or pull-down — as a type parameter, so an operation intended for one mode fails to compile when the pin is in another. The Rust Embedded Book documents the pattern as C-PIN-STATE. The pin’s mode is not discovered by events; the program sets it, and after that the type knows it.

One standard-library method shows the single-type version of the same idea: JoinHandle::join takes self by value, so a thread handle cannot be joined twice — the first join consumes it. Typestate extends that move-based thinking across several types.

Most real systems mix the two designs. The enum carries the state wherever values are stored and transported; typestate guards the operations that must happen in order. The boundary between them is explicit code, and writing that boundary down is usually cheaper than defending it by convention.

<— back to rust