Allow Multiple Guesses with Looping

Want to add a loop? All you need is the keyword loop:

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!"),
        }
    }
}

This will create an infinite loop! You will never stop guessing...

So... let's end this loop. How do you do that? By adding a break. Edit the above code so that when Ordering::Equal is returned, you get this:

Ordering::Equal => {
    println!("You win!");
    break;
}

Last updated