]> git.proxmox.com Git - rustc.git/blob - src/doc/book/listings/ch09-error-handling/listing-09-13/src/main.rs
New upstream version 1.62.1+dfsg1
[rustc.git] / src / doc / book / listings / ch09-error-handling / listing-09-13 / src / main.rs
1 use rand::Rng;
2 use std::cmp::Ordering;
3 use std::io;
4
5 // ANCHOR: here
6 pub struct Guess {
7 value: i32,
8 }
9
10 impl Guess {
11 pub fn new(value: i32) -> Guess {
12 if value < 1 || value > 100 {
13 panic!("Guess value must be between 1 and 100, got {}.", value);
14 }
15
16 Guess { value }
17 }
18
19 pub fn value(&self) -> i32 {
20 self.value
21 }
22 }
23 // ANCHOR_END: here
24
25 fn main() {
26 println!("Guess the number!");
27
28 let secret_number = rand::thread_rng().gen_range(1..=100);
29
30 loop {
31 println!("Please input your guess.");
32
33 let mut guess = String::new();
34
35 io::stdin()
36 .read_line(&mut guess)
37 .expect("Failed to read line");
38
39 let guess: i32 = match guess.trim().parse() {
40 Ok(num) => num,
41 Err(_) => continue,
42 };
43
44 let guess = Guess::new(guess);
45
46 match guess.value().cmp(&secret_number) {
47 Ordering::Less => println!("Too small!"),
48 Ordering::Greater => println!("Too big!"),
49 Ordering::Equal => {
50 println!("You win!");
51 break;
52 }
53 }
54 }
55 }