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.

RustData Integrity

Code

rustsnippet
29 lines
#[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

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:`.