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