Simple menu, for a newbie?

Hi, I have this piece and ran fine. Another way ?

use std::{fs, io};

fn cat() {
    println!("Hello Cat !");
}

fn dog() {
    println!("Hello Dog !");
}

fn main_menu() {
    // reading option    
    loop {
    println!("-----------------------\n * PANEL *\n-----------------------
[1] Cat
[2] Dog      
[0] Exit\n
Welcome, select option:
----------------------- ");
        let mut input = String::new();
        let stdin_preset = io::stdin();
        stdin_preset.read_line(&mut input).unwrap();
        match input.trim_end() { // this method kill "\n" at the end
            "1" => { println!("Choice Cat !");
                    cat();
                },
            "2" => { println!("Choice Dog !");
                    dog();
                },
            "0" => { println!("Bye!");
                    break;
                },
            _ => println!("Incorrect. Choice [0-2]"),
        }
    }
}

fn main() {
    main_menu();    
}

It's a good usage of the match statement. I suggest everybody to format their code with rustfmt. If you get used to its formatting, it'll become much easier to read other peoples code.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.