Match On An Enum To Drive A State Machine
Advance a traffic light through cycles by matching the current variant and returning the next one, so impossible transitions cannot be written.
Code
#[derive(Debug, Clone, Copy, PartialEq)]
enum Light { Red, Yellow, Green }
impl Light {
// match 穷尽每个变体:加新灯时编译器直接指出漏臂
fn next(self) -> Self {
match self {
Light::Red => Light::Green,
Light::Green => Light::Yellow,
Light::Yellow => Light::Red,
}
}
}
fn main() {
let mut light = Light::Red;
for step in 0..6 {
println!("step {step}: {light:?}");
light = light.next(); // 消费 self、返回新状态,旧值一并失效
}
// 用 match 解读状态:每臂独立逻辑
let action = match light {
Light::Red => "stop",
Light::Yellow => "slow down",
Light::Green => "go",
};
println!("now: {light:?} -> {action}");
}Inside the snippet
One way to read it: the functions next and main, doing all the work.
Iteration happens inside for step in 0..6 — everything outside it runs once. Pattern matching via match forces each shape of the value to be handled.
Watch out for
- Nothing to add to the project before running it.
Using it
Signature: fn next(self) -> Self
The run emits 2 labeled sections — step, now: — one per step.
Launch the file; main takes over and steps through next.
Key statements
let action = match light {
Light::Red => "stop",
Light::Yellow => "slow down",
Light::Green => "go",
};
fn next(self) -> Self {
match self {
Light::Red => Light::Green,
Light::Green => Light::Yellow,
Light::Yellow => Light::Red,
}
}
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Match On An Enum To Drive A State Machine print when run?
- Running the file directly is enough — expect labeled output lines such as `step`, `now:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.