How do you model a program so that it reflects real-world state, and that undesired or impossible states are unreachable?
Especially in safety-focused systems programming related to communication, interfaces, or I/O, the typestate pattern helps to ensure correctness and safety. Encoding state in type signatures exposes only valid transitions and operations. This reduces the need of runtime errors and even checks and leads to very pleasant APIs.
The Rust language has some unique features which enable downright beautiful typestate patterns. One idiomatic way to implement the state machine pattern is a struct with a generic parameter for each state. Such a StateMachine
implements the operations of ``, and the initial state has a 'new
' implementation. Transitions are realized by implementing `std::convert::From` (automagically implementing `std::convert::Into`). Due to the type sign