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

