How to Build a Simple Game Loop in Rust

Build a Rust game loop using an infinite loop block with a break condition to handle input and exit gracefully.

A game loop in Rust uses an infinite loop block that runs until a break statement exits it. The loop handles input, updates game state, and checks for exit conditions on every iteration.

use std::io;

fn main() {
    let secret_number = 42;

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

        if guess == secret_number {
            println!("You win!");
            break;
        }
    }
}

Run the code with cargo run to test the loop.