[SOLVED] Rust if else and user input | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

[SOLVED] Rust if else and user input

Where did i wrong here 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"); }; } When i type y it's not print "Please input your guess" and instead print "Invalid command"

8th Feb 2022, 12:43 PM
EsaKurniawan
11 Answers
+ 2
Your input coming from the keyboard will contain the trailing newline character. Before comparing you have to remove that character. For example: 1) let is_start = is_start.trim_end(); You need the let because trim_end() will return a different data type. 2) is_start.truncate(1); This cuts the length down to one. Disadvantage: it will accept y, yes, yeppediddlidooah, ... everything that start with a y (other letters accordingly) 3) is_start.truncate(is.start.len()-1); This chops off the last character. May cause problems on other OSes that use more than a \n to end a line.
8th Feb 2022, 1:52 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 2
Ani Jona 🕊 use your first method, and now it's working. thanks
8th Feb 2022, 1:59 PM
EsaKurniawan
+ 2
Your "n" part is not a single expression, wrap it in curlies { }
8th Feb 2022, 2:51 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Sure, you can use a match expression.
8th Feb 2022, 2:04 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
I would not expect that much of a difference, let alone any significance! But generally, a match I would expect to be more efficient because it avoids a repeated comparison.
8th Feb 2022, 2:13 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 1
Thanks for your help man Ani Jona 🕊
8th Feb 2022, 2:58 PM
EsaKurniawan
+ 1
You're welcome :)
8th Feb 2022, 4:13 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
0
And one more thing
8th Feb 2022, 2:01 PM
EsaKurniawan
0
Can i do above checking without if else in rust?
8th Feb 2022, 2:02 PM
EsaKurniawan
0
Which one is more efficient is rust match expression or if else above?
8th Feb 2022, 2:09 PM
EsaKurniawan
0
match is_start { "y" => println!("Please input your guess"), "n" => println!("Successfully quit the game") println!("If you want to start game again, please restart your terminal"), _ => println!("Invalid command") }; Why when i do this it give me an error?
8th Feb 2022, 2:27 PM
EsaKurniawan