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 std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
rust
use axum::{ extract::State, routing::{get, post, MethodRouter}, Json, Router,
Self-documenting routes in Axum
builder-pattern
closures
shared-state
Intermediate
8 steps
rust
use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::path::Path;
Parsing INI files in Rust
parsing
file-io
hashmap
Intermediate
9 steps
rust
use axum::{ extract::{Path, Query}, http::Uri, response::{IntoResponse, Redirect},
Building HTTP redirect handlers in Axum
redirects
extractors
url-handling
Intermediate
7 steps
rust
use axum::{ body::Body, extract::MatchedPath, http::{Request, StatusCode},
An admin route guard in Axum middleware
middleware
authorization
request-extensions
Intermediate
7 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.