Puzzle 2: Explanation
Let’s find out how Rust handles string operations while taking input from users.
We'll cover the following...
We'll cover the following...
Test it out
Hit “Run” to see the code’s output.
use std::io::stdin; fn main() { println!("What is 3+2? Type your answer and press enter."); let mut input = String::new(); stdin() .read_line(&mut input) .expect("Unable to read standard input"); if input == "5" { println!("Correct!"); } else { println!("Incorrect!"); } println!("{:#?}", input); }
What is 3 + 2? Not 5!
Explanation
Normally, 3+2 would equal 5, but that’s not how Rust handles strings! To find out why, add the following line to the end of the program:
println!("{:#?}", input);
With this new line, we’ll be able to see the full-string Rust returns from stdin
.
...