Guessing Game - Random Numbers & Game Loops in Rust | Rust by Examples (Lesson 3)
Video: Guessing Game - Random Numbers & Game Loops in Rust | Rust by Examples (Lesson 3) by Taught by Celeste AI - AI Coding Coach
Watch full page →Guessing Game - Random Numbers & Game Loops in Rust
Build a simple interactive number guessing game in Rust by leveraging external crates, random number generation, and control flow constructs. This example demonstrates how to add dependencies, generate a secret number, handle user input, and use pattern matching to guide the player toward the correct guess.
Code
use rand::Rng; // Trait for random number generation
use std::cmp::Ordering; // For comparing values
use std::io; // For reading user input
fn main() {
println!("Guess the number!");
// Generate a random secret number between 1 and 100 (inclusive)
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
println!("Please input your guess.");
let mut guess = String::new();
// Read user input from stdin
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
// Convert input string to unsigned 32-bit integer, handle parse errors
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Please enter a valid number!");
continue; // Restart loop if input invalid
}
};
println!("You guessed: {}", guess);
// Compare guess to secret number
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break; // Exit loop when guessed correctly
}
}
}
}
Key Points
- Use
cargo add randto add therandcrate for random number generation. - Generate random numbers with
rand::thread_rng().gen_range(start..=end)for inclusive ranges. - Compare values using
std::cmp::Orderingand handle outcomes withmatchexpressions. - Create interactive loops with
loopand exit them usingbreakwhen conditions are met. - Read and parse user input safely, handling invalid inputs gracefully to keep the game running smoothly.