Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.87 KB | None | 0 0
  1. extern crate rand;
  2.  
  3. use rand::Rng;
  4. use std::io;
  5. use std::cmp::Ordering;
  6.  
  7. fn main() {
  8.  
  9.     // Generate random unsigned int32 from range of [0, 101).
  10.     let random_number: u32 = rand::thread_rng().gen_range(0, 101);
  11.  
  12.     // (DEBUG ONLY) Print it out.
  13.     println!("DEBUG The random number is: {}", random_number);
  14.  
  15.     loop {
  16.         println!("Try to guess the random number!");
  17.  
  18.         // Create a new String (alloc some memory for it, too) to store the user input.
  19.         // Note: We set it as mutable because we need to modify it after initialization.
  20.         let mut guess = String::new();
  21.  
  22.         // stdin() returns a handle to stdin, and read_line takes in a reference (borrowed)
  23.         // to the guess (which gets populated inside the method). Then, the return value of
  24.         // that is either Err or Ok, which is why we use expect to catch cases of Err.
  25.         io::stdin().read_line(&mut guess).expect("Failed to read line.");
  26.         // Note: this is kind of equivalent to:
  27.         /*
  28.         match io::stdin().read_line(&mut guess) {
  29.             Ok(_) => (), // do nothing.
  30.             Err(_) => {
  31.                 // Print error and exit!
  32.                 println!("Failed to read line."); std::process::exit(1);
  33.             }
  34.         };
  35.         */
  36.  
  37.         // Now we convert from String to an unsigned int32 (so we can compare with the random_number).
  38.         // If the return value from parse() is an Err, we retry the method. If it's an Ok,
  39.         // we extract the value and that's what gets assigned to guess_num.
  40.         let guess_num: u32 = match guess.trim().parse() {
  41.             Ok(num) => num,
  42.             Err(_) => continue,
  43.         };
  44.  
  45.         println!("User input is: {}", guess_num);
  46.  
  47.         // We compare the guess with a reference to the random_number, and based on the result of
  48.         // the comparison, we print a hint out or exit.
  49.         match guess_num.cmp(&random_number) {
  50.             Ordering::Less => println!("Too low!"),
  51.             Ordering::Greater => println!("Too High!"),
  52.             Ordering::Equal => {
  53.                 println!("Correct!"); break;
  54.             }
  55.         };
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement