DEV Community

Stacy Roll
Stacy Roll

Posted on

Logic of a menu greater than 2 options in rust 🧠

Making a menu and matching functions is easy logic. Now when we have several options to match we need another logic to handle that event. In this article I am going to show you with k_board how to manage the logic for your program.

cargo add k_board

use k_board::{Keyboard, Keys};

fn main() {
    let mut number: i8 = 0;
    menu(&mut number, 0);
    for key in Keyboard::new() {
        match key {
            Keys::Up => menu(&mut number, -1),
            Keys::Down => menu(&mut number, 1),
            Keys::Enter => break,
            _ => {}
        }
    }
    //then match output
}

fn menu(operation: &mut i8, selection: i8) {
    std::process::Command::new("clear").status().unwrap();
    if *operation >= 0 && *operation <= 3 {
        *operation += selection;
        if *operation == -1 {
            *operation += 1;
        }
        if *operation == 4 {
            *operation -= 1;
        }
    }
    let mut op: Vec<char> = vec![' ', ' ', ' ', ' '];
    for i in 0..4 {
        if i == *operation {
            op[i as usize] = '*';
        }
    }
    println!("{} a\n{} b\n{} c\n{} d", op[0], op[1], op[2], op[3]);
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)