Created
April 6, 2017 20:56
-
-
Save ak9999/62cf83916523ca18ad2e009459e3b342 to your computer and use it in GitHub Desktop.
Guessing Game Tutorial from Rust docs using the `print!` macro.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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