Skip to content

Instantly share code, notes, and snippets.

@delarco
Created February 7, 2024 11:48
Show Gist options
  • Save delarco/02d666eb5a585ff34acda49ba7b95cf3 to your computer and use it in GitHub Desktop.
Save delarco/02d666eb5a585ff34acda49ba7b95cf3 to your computer and use it in GitHub Desktop.
Rust Guessing Game
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
const MIN_NUMBER: u32 = 1;
const MAX_NUMBER: u32 = 100;
let secret_number = rand::thread_rng().gen_range(MIN_NUMBER..=MAX_NUMBER);
loop {
println!("Input your guess ({MIN_NUMBER} to {MAX_NUMBER}):");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("error");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Not a number!");
continue;
}
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment