Ideas on improving a transition state implementation of program flow

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.");
} `

The obvious thing to improve is that if the table could be much larger, then you should avoid the linear search in .iter().find(), because it gets slower the more elements it searches through.

  • If the numbers are sparse (the largest number is much bigger than the size of the table) then you should use a HashMap or BTreeMap instead of a Vec.
  • If the numbers are dense (most possible inputs have a transition) then you should use a Vec where the position in the Vec is also the input number, so you can index the Vec instead of searching it.
  • If the numbers will always be 0-9, so there are only 10 possible inputs, then you should use an array [Transition; 10], like the Vec in the previous option but fixed size.
1 Like