简体   繁体   中英

Rust string comparison failing

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.

Looks like read_line appends new line to string which means a comparison of "Hello" with "Hello\r\n" will of course fail. I actually found a relevant stack overflow answer: Weird behaviour when using read_line in a loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM