Working with Rust
Guessing Game in Rust
An example program of the classic guess a number between 1-100 game. This shows how to generate a rando number, gather user input, validate the result, and check against the guess.
Requires rand
dependency in your Cargo.toml
Play with example in Rust Playground.
use rand::Rng;
use std::io;
use std::io::Write;
fn main() {
// Set number, last number in range is not included so +1
let x = rand::thread_rng().gen_range(1..101);
// Track number of guesses
let mut count = 1;
// Prompt
println!("Guess a number from 1-100:");
loop {
print!("Guess #{}: ", count);
// Output gets flushed on new lines
// To prompt on same line requires manual flush the output
let _ = io::stdout().flush();
// Get user input
let mut input = String::new();
io::stdin().read_line(&mut input).expect("User Input Error");
// validate user input
let guess = match input.trim().parse::<i32>() {
Ok(x) => x,
Err(_err) => {
println!(" > Not a number. Try again");
continue;
}
};
if guess > x {
println!(" > {} is too high", guess);
}
else if guess < x {
println!(" > {} is too low", guess);
}
else {
println!(" 🎉 Congrats! It was {}, it took {} guesses", guess, count);
break;
}
count += 1;
}
}