Ideas on improving a transition state implementation of program flow

⚓ Rust    📅 2025-11-05    👤 surdeus    👁️ 6      

surdeus

I have implemented a state table in Rust in a very simple way, as shown below and I'm new to rust and I'm wondering: What would more experienced rustaceans would suggest as implementation improvements or options?

let table: Vec<Transition> = vec!\[

        Transition { input: 0, nextstate: print_input },
        Transition { input: 1, nextstate: print_input },

       /* clipped repetitive code */
        Transition { input: 8, nextstate: negate_input },
        Transition { input: 9, nextstate: exit_input },

    \];

let mut running = true;
    let stdin = io::stdin();
    while running {
        print!("Enter a digit 0-9 (or 'q' to quit): ");
        io::stdout().flush().ok();
        let mut line = String::new();
        if stdin.read_line(&mut line).is_err() {
            eprintln!("Failed to read input");
            break;
        }
        let line = line.trim();
        if line.eq_ignore_ascii_case("q") {
            println!("Quitting.");
            break;
        }
        match line.parse::<i16>() {
            Ok(val) if (0..=9).contains(&val) => {
                if let Some(entry) = table.iter().find(|e| e.input == val) {
                    // call the referred function before asking for next input
                    running = (entry.nextstate)(val);
                } else {
                    println!("No transition for input {}", val);
                }
            }
            \_ => {
                println!("Please enter a single digit 0-9 or 'q' to quit.");
            }

        }

    }

    println!("State machine terminated.");
} `

2 posts - 2 participants

Read full topic

🏷️ Rust_feed