Skip to content

Instantly share code, notes, and snippets.

@ak9999
Created April 6, 2017 20:56
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 ak9999/62cf83916523ca18ad2e009459e3b342 to your computer and use it in GitHub Desktop.
Save ak9999/62cf83916523ca18ad2e009459e3b342 to your computer and use it in GitHub Desktop.
Guessing Game Tutorial from Rust docs using the `print!` macro.
extern crate rand; // rand crate for generating random numbers
use std::io; // io library from standard library
use std::io::Write; // Needed for flushing stdout after print.
use std::cmp::Ordering; // For comparing values
use rand::Rng; // from rand crate
fn main() {
println!("Guess the number, from 0 to 100."); // Greet user
let secret_number = rand::thread_rng().gen_range(0, 101);
loop {
print!("Please input your guess: "); // Prompt user
io::stdout().flush().unwrap(); // Flush
let mut guess = String::new(); // Allocate new mutable String
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!("Your guess was too small."),
Ordering::Greater => println!("Your guess was too big."),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
println!("The secret number is: {}", secret_number);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment