liveBook · Manning

Type state

As explained in Idiomatic Rust

A type-safe state machine is a state-machine design whose valid states and transitions are enforced by the programming language's type system.

Type state encodes an object’s state in its type, letting Rust’s compiler check which transitions are valid. It is useful when software state must stay in sync with an external system, such as a light bulb. section 7.6

A Rust type-state design typically:

  • Uses marker types and a generic struct to represent each state. section 7.6
  • Implements methods only for the states in which they are valid. section 7.6
  • Consumes the current value and returns a new value with a different state type when transitioning. section 7.6
Listing 7.5 Adding state transitions
impl LightBulb<On> {                       #1
    fn turn_off(self) -> LightBulb<Off> {  #2
        LightBulb::<Off>::default()
    }
    fn state(&self) -> &str {     #3
        "on"
    }
}

impl LightBulb<Off> {                      #4
    fn turn_on(self) -> LightBulb<On> {
        LightBulb::<On>::default()
    }
    fn state(&self) -> &str {
        "off"
    }
}

The light-bulb example shows state-specific methods consuming one typed value and returning the other state. section 7.6

User sessions

A session can move from anonymous to authenticated, update properties while authenticated, and then log out. Methods are attached to the relevant state types, so only defined transitions are available. section 8.1

How Idiomatic Rust covers it

How deep it goes
Defines states and transitions and demonstrates state-specific methods; omits database lookup and validation during session resumption.
Examples
Demonstrates light-bulb transitions and a user session with authentication, property updates, and logout.
What it assumes
Assumes familiarity with Rust traits and generics, then applies marker types and PhantomData to encode states.
What you can do after
Build a Rust state machine whose state-specific methods and transitions are checked by the type system.
How it connects
Connects Rust generics, traits, and ownership to state machines.

Also explained in

Compare how 2 books explain type state →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.