rust 47 lines · 9 steps

A turnstile state machine in Rust

A finite state machine models a coin-operated turnstile by matching on the current state paired with an incoming event.

Explained by highlit
1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2enum State {
3 Locked,
4 Unlocked,
5}
6 
7enum Event {
8 Coin,
9 Push,
10}
11 
12struct Turnstile {
13 state: State,
14 coins_collected: u32,
15 passages: u32,
16}
17 
18impl Turnstile {
19 fn new() -> Self {
20 Turnstile {
21 state: State::Locked,
22 coins_collected: 0,
23 passages: 0,
24 }
25 }
26 
27 fn dispatch(&mut self, event: Event) {
28 self.state = match (self.state, event) {
29 (State::Locked, Event::Coin) => {
30 self.coins_collected += 1;
31 State::Unlocked
32 }
33 (State::Locked, Event::Push) => {
34 eprintln!("still locked, insert a coin first");
35 State::Locked
36 }
37 (State::Unlocked, Event::Push) => {
38 self.passages += 1;
39 State::Locked
40 }
41 (State::Unlocked, Event::Coin) => {
42 eprintln!("already unlocked, coin refunded");
43 State::Unlocked
44 }
45 };
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Modeling states and events as enums makes illegal states unrepresentable and every transition explicit.
  2. 2Matching on a tuple of state and event lets the compiler enforce that you handle every combination.
  3. 3Each match arm can both compute the next state and perform side effects like counting.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A turnstile state machine in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code