Skip to content

Instantly share code, notes, and snippets.

@ls0f
Created March 5, 2015 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ls0f/5cd494c6461fbd15ca1e to your computer and use it in GitHub Desktop.
Save ls0f/5cd494c6461fbd15ca1e to your computer and use it in GitHub Desktop.
rust guess game
use std::io;
use std::rand;
use std::cmp::Ordering;
fn cmp(a: u32, b: u32) -> Ordering {
if a < b { Ordering::Less }
else if a > b { Ordering::Greater }
else { Ordering::Equal }
}
fn main() {
println!("Guess the number!");
let secret_number = (rand::random::<u32>() % 100) + 1;
loop {
println!("Please input your guess.");
let input = io::stdin().read_line().ok().expect("fail to read line");
let input_num: Option<u32> = input.trim().parse();
let num = match input_num {
Some(num) => num,
None => {
println!("Please input a number!");
continue;
}
};
println!("You guessed: {}", num);
match cmp(num, secret_number) {
Ordering::Greater => println!("Greater"),
Ordering::Less => println!("Less"),
Ordering::Equal => {println!("you guess");break;},
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment