Hi, sorry. I try to do a menu in practice.
how do that using match ?
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");
};
}
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.
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.