How to Implement a Finite State Machine in Rust

Implement a Finite State Machine in Rust using enums for states and match expressions for transitions.

Implement a Finite State Machine in Rust by defining an enum for states and using match to handle transitions.

#[derive(Debug, PartialEq)]
enum State { Idle, Running, Stopped }

fn transition(current: State, action: &str) -> State {
    match (current, action) {
        (State::Idle, "start") => State::Running,
        (State::Running, "stop") => State::Stopped,
        _ => current,
    }
}

fn main() {
    let mut s = State::Idle;
    s = transition(s, "start");
    println!("{s:?}");
}