How do I match on a string read from standard inpu

2019-02-17 23:07发布

问题:

This question already has an answer here:

  • Why doesn't my user input from stdin match correctly? 3 answers

In an exercise to learn Rust, I'm trying a simple program that will accept your name, then print your name if it's Valid.

Only "Alice" and "Bob" are valid names.

use std::io;

fn main() {
    println!("What's your name?");
    let mut name = String::new();

    io::stdin().read_line(&mut name)
    .ok()
    .expect("Failed to read line");

    greet(&name);
}

fn greet(name: &str) {
    match name {
        "Alice" => println!("Your name is Alice"),
        "Bob"   => println!("Your name is Bob"),
        _ => println!("Invalid name: {}", name),
    }
}

When I cargo run this main.rs file, I get:

What's your name?
Alice
Invalid name: Alice

Now, my guess is, because "Alice" is of type &'static str and name is of type &str, maybe it's not matching correctly...

回答1:

I bet that it isn't caused by type mismatch. I place my bet on that there are some invisible characters (new line in this case). To achieve your goal you should trim your input string:

match name.trim() {
    "Alice" => println!("Your name is Alice"),
    "Bob"   => println!("Your name is Bob"),
    _ => println!("Invalid name: {}", name),
}


标签: rust