Confused with menu

Hi, sorry. I try to do a menu in practice.
how do that using match ? :sweat:

use std::io;

fn main() {
    println!("Welcome to Guessing number game");
    
    println!("Would you like to start the game? (y/n)");
    let mut is_start = String::new();
    
    io::stdin()
      .read_line(&mut is_start)
      .expect("Failed to read line.");
      
    if is_start == "y" {
      println!("Please input your guess");
    } else if is_start == "n" {
      println!("Successfully quit the game");
      println!("If you want to start game again, please restart your terminal");
    } else {
      println!("Invalid command");
    };
    
}

Confused with the thread
SCNR

Seriously, what's your question or problem? How should we help you without sufficient information? Please describe your problem in detail and post your error messages if there are any.

Hint: try debug printing is_start see what it contains.

ERROR IN MATCH: expected struct String, found &str

use std::io;

fn main() {
    println!("Welcome to Guessing number game");
    
    println!("Would you like to start the game? (y/n)");
    let mut is_start = String::new();
    
    io::stdin()
      .read_line(&mut is_start)
      .expect("Failed to read line.");
    
    is_start = is_start.trim_end().to_string();
    match is_start {
        "y" => println!("Please input your guess"),
        "n" => println!("Quit"),
        _ => Todo!;
    };
//     if is_start == "y" {
//       println!("Please input your guess");
//     } else if is_start == "n" {
//       println!("Successfully quit the game");
//       println!("If you want to start game again, please restart your terminal");
//     } else {
//       println!("Invalid command");
//     };

    
}

You could avoid storing the response and save yourself some trouble.

use std::io;

fn main() {
    println!("Welcome to Guessing number game");
    
    println!("Would you like to start the game? (y/n)");
    for line in io::stdin().lines() {
        match line.expect("Failed to read line").as_str() {
            "y" => {
                println!("Please input your guess");
                // function to handle "y" case
                break;
            },
            "n" => {
                println!("Successfully quit the game");
                println!("If you want to start game again, please restart your terminal");
                // function to handle "n" case
                break;
            },
            _ => println!("Invalid command, please input again"),
        }
    }
}

@edit: Or even better, write a function to handle the user input and another function to handle game mechanics.

match is_start.as_str() {
"y" => println!("Please input your guess"),
"n" => println!("Quit"),
_ => println!("Invalid command"),
}

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.