box-o-sand/rustbook/guessing_game/src/main.rs

37 lines
818 B
Rust
Raw Normal View History

2016-08-31 12:00:15 +00:00
extern crate rand;
2016-08-31 02:49:38 +00:00
use std::io;
2016-08-31 12:00:15 +00:00
use std::cmp::Ordering;
use rand::Rng;
2016-08-31 02:49:38 +00:00
fn main() {
println!("Guess the number!");
2016-08-31 12:00:15 +00:00
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
2016-08-31 02:49:38 +00:00
2016-08-31 12:00:15 +00:00
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
2016-08-31 02:49:38 +00:00
2016-08-31 12:00:15 +00:00
println!("You guessed: {}", guess);
2016-08-31 02:49:38 +00:00
2016-08-31 12:00:15 +00:00
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
},
}
}
2016-08-31 02:49:38 +00:00
}