This has me going crazy because it should be incredibly simple. I've just started learning Rust and was playing around with if statements. I'm failing to perform simple string comparisons, however.
I'm expecting my code to accept console input and if that input reads "Hello", then "Hi" should be printed. Unfortunately that isn't happening, and instead I get the else option: "I don't understand". <-- pretty apt.
use std::io;
fn main() {
println!("Say a greeting!");
loop {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(_) => {
let res = say_hi_back(input);
println!("{}", res);
}
Err(error) => println!("error: {}", error),
}
}
}
fn say_hi_back(greeting: String) -> String {
let response = if greeting == "Hello" {
"Hi".to_string()
} else {
"I don't understand".to_string()
};
return response;
}
Sorry this is such a noob question, but I'm wondering why greeting != "Hello" when given as input to the console? At first I thought it was some type error, but as far as I know you can freely compare &str types with String types.