rustbook

Toy programs and snippets for The Rust Programming Language book
Log | Files | Refs

main.rs (1352B)


      1 use std::io;
      2 use rand::Rng;
      3 use std::cmp::Ordering;
      4 
      5 pub struct Guess {
      6     value: u32,
      7 }
      8 
      9 impl Guess {
     10     pub fn new(value: u32) -> Guess {
     11         if value < 1 || value > 100 {
     12             panic!("Guess is out of bounds (1-100)");
     13         }
     14         Guess {value}
     15     }
     16 
     17     pub fn get_value(&self) -> u32 {
     18         self.value
     19     }
     20 }
     21 
     22 fn main() {
     23     println!("Guess my number! (1-100)");
     24     let number = rand::thread_rng().gen_range(1, 101);
     25 
     26     loop {
     27         println!("Input Guess:");
     28 
     29         let mut guess = String::new();
     30         io::stdin()
     31             .read_line(&mut guess)
     32             .expect("Failed to read line");
     33         let guess = guess.trim();
     34         if guess == "quit" {
     35             println!("quitting game!");
     36             break;
     37         }
     38 
     39         let guess: Guess = match guess.parse() {
     40             Ok(num) => Guess::new(num),
     41             Err(_) => {
     42                 println!("{} is not a number!", guess);
     43                 continue;
     44             }
     45         };
     46         println!("Guess {} accepted!", guess.get_value());
     47 
     48         match guess.get_value().cmp(&number) {
     49             Ordering::Less => println!("Too Small!"),
     50             Ordering::Greater=> println!("Too Large!"),
     51             Ordering::Equal=> {
     52                 println!("Correct! The number is {}", number);
     53                 break;
     54             }
     55         }
     56     }
     57 }