Handling Bad Input

Here's our current code:

main.rs
use std::io;
use std::cmp::Ordering;

fn main() {
    println!("Guess the number!");

    let secret_number = 42;

    println!("The secret number is: {}", secret_number);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

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

        let guess: u32 = guess.trim().parse()
            .expect("Please type a number!");

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            },
        }
    }
}

What's the problem now? Well, right now, if you enter something that is non-numeric, you get an error and it stops the program. Let's handle that!

let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => continue,
};

Just like we are doing when we compare the guess, we can also use match on the results of parse, which only has two varients. We use the _ because we don't care what the content of Err is, we just want to continue.

What if we do want to output the content of Err? Let's change the code again to print out the message.

let guess: u32 = match guess.trim().parse() {
              Ok(num) => num,
              Err(msg) => {
                println!("{}", msg);
                continue;
              },
          };

Here's what the output looks like now:

Last updated