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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Modeling states and events as enums makes illegal states unrepresentable and every transition explicit.
- 2Matching on a tuple of state and event lets the compiler enforce that you handle every combination.
- 3Each match arm can both compute the next state and perform side effects like counting.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-turnstile-state-machine-in-rust-explained-rust-afaa/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.