5

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...

3
  • 2
    Try match name.trim() { ... }. I can't test it at the moment but I bet there's a newline character in the input. Commented Jul 21, 2015 at 14:14
  • that was it... i always forget about that, thanks! If you post an answer, i'll upvote and accept. Commented Jul 21, 2015 at 14:15
  • 1
    If there had been type mismatch it would not have compiled. You can see precisely what’s in a string by formatting it with Debug ({:?}) instead of Display ({}), too. Commented Jul 22, 2015 at 1:01

1 Answer 1

9

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),
}
Sign up to request clarification or add additional context in comments.

1 Comment

A.B. hasn't submitted an answer yet, so i'll just accept yours.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.