0

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!

1 Answer 1

1

The result possibly contains a trailing newline.

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.