Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate rand;
- use rand::Rng;
- use std::io;
- use std::cmp::Ordering;
- fn main() {
- // Generate random unsigned int32 from range of [0, 101).
- let random_number: u32 = rand::thread_rng().gen_range(0, 101);
- // (DEBUG ONLY) Print it out.
- println!("DEBUG The random number is: {}", random_number);
- loop {
- println!("Try to guess the random number!");
- // Create a new String (alloc some memory for it, too) to store the user input.
- // Note: We set it as mutable because we need to modify it after initialization.
- let mut guess = String::new();
- // stdin() returns a handle to stdin, and read_line takes in a reference (borrowed)
- // to the guess (which gets populated inside the method). Then, the return value of
- // that is either Err or Ok, which is why we use expect to catch cases of Err.
- io::stdin().read_line(&mut guess).expect("Failed to read line.");
- // Note: this is kind of equivalent to:
- /*
- match io::stdin().read_line(&mut guess) {
- Ok(_) => (), // do nothing.
- Err(_) => {
- // Print error and exit!
- println!("Failed to read line."); std::process::exit(1);
- }
- };
- */
- // Now we convert from String to an unsigned int32 (so we can compare with the random_number).
- // If the return value from parse() is an Err, we retry the method. If it's an Ok,
- // we extract the value and that's what gets assigned to guess_num.
- let guess_num: u32 = match guess.trim().parse() {
- Ok(num) => num,
- Err(_) => continue,
- };
- println!("User input is: {}", guess_num);
- // We compare the guess with a reference to the random_number, and based on the result of
- // the comparison, we print a hint out or exit.
- match guess_num.cmp(&random_number) {
- Ordering::Less => println!("Too low!"),
- Ordering::Greater => println!("Too High!"),
- Ordering::Equal => {
- println!("Correct!"); break;
- }
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement