Using Result type's Err variant more effectively

Dear Rustaceans,

I need help to modify with the below code.

use rand::Rng;
use std::cmp::Ordering;
use std::io;

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

    let secret_number = rand::thread_rng().gen_range(1..101);

    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 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        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;
            }
        }
    }
}

The above code snippet is a copy-paste from "The Rust Programming Language" book/doc from official Rust site.

When I run this code it asks to input the guess and if I input anything except number the code just asks again to input the guess.

image

I want to modify the code so that if Result type is Err variant then it will print a warning message first (something like "Please input number only") and then will ask to input the guess again. I believe modification is required in the below context, but not sure.

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

Thanks for your help!

  • Supratik

Try this:

let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => {
        println!("That's not a number!");
        continue
    },
};

Awesome :smiley:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.