cloudy_eclispse
cloudy_eclispse

Reputation: 343

Matching Strings with string literals in Rust

I'm learning Rust and have been stuck on this piece of code that matches a string with some literals for a while.

while done_setup == false {
        println!("Enter difficultly mode you wish to play (Easy/Medium/Hard):");
        let mut difficulty = String::new();
        io::stdin()
            .read_line(&mut difficulty)
            .expect("Invalid input, aborting");
        match difficulty.as_str() {
            "Easy" => {num_guesses = 10;},
            "Medium" => {num_guesses = 7;},
            "Hard" => {num_guesses = 3;},
            _ => {
                println!("Pls enter a valid difficulty mode!");
                continue;
            },
        }
        println!("You are playing in {} mode, you have {} tries!", difficulty, num_guesses);
        done_setup = true;
    }

Apparently the pattern never matches with "Easy", "Medium" or "Hard" since user input ALWAYS flows to the default case. I've read similar SO questions and I understand that String objects are not the same as literals (str), but shouldn't difficulty.as_str() take care of that?

I'm looking for a clean & "proper" way to code this, any suggestions welcome & thanks in advance!

Upvotes: 0

Views: 1203

Answers (1)

phimuemue
phimuemue

Reputation: 35983

The result possibly contains a trailing newline.

trim can be used to strip away leading and trailing whitespace.

Upvotes: 1

Related Questions