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

38 lines
830 B
Rust
Raw Normal View History

2017-12-22 03:27:49 +00:00
extern crate rand;
2017-12-22 03:49:29 +00:00
use std::cmp::Ordering;
2017-12-22 03:25:39 +00:00
use std::io;
2017-12-22 03:27:49 +00:00
use rand::Rng;
2017-12-22 03:25:39 +00:00
2016-08-31 02:49:38 +00:00
fn main() {
2017-12-22 03:25:39 +00:00
println!("Guess the number!");
2017-12-22 03:27:49 +00:00
let secret_number = rand::thread_rng().gen_range(1, 101);
2017-12-22 04:05:33 +00:00
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);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
2017-12-22 03:49:29 +00:00
}
2016-08-31 02:49:38 +00:00
}