Skip to content

Instantly share code, notes, and snippets.

@cruor99
Created February 22, 2015 19:34
Show Gist options
  • Save cruor99/7fa825b293568ad13388 to your computer and use it in GitHub Desktop.
Save cruor99/7fa825b293568ad13388 to your computer and use it in GitHub Desktop.
use std::old_io;
use std::rand;
use std::cmp::Ordering;
fn main() {
println!("Guess the number!");
let secret_number = (rand::random::<u32>() % 100) +1; //secret_number: i32
println!("Please input your guess.");
loop {
let input = old_io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Result<u32, _> = input.trim().parse();
let num = match input_num {
Ok(num) => num,
Err(_) => {
println!("Please input a number!");
continue;
}
};
println!("You guessed: {:?}", num);
match cmp(num, secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
return;
},
}
}
}
fn cmp(a: u32, b: u32) -> Ordering {
if a < b { Ordering::Less }
else if a > b { Ordering::Greater }
else { Ordering::Equal }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment