summaryrefslogtreecommitdiffstats
path: root/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 12:02:58 +0000
commit698f8c2f01ea549d77d7dc3338a12e04c11057b9 (patch)
tree173a775858bd501c378080a10dca74132f05bc50 /src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src
parentInitial commit. (diff)
downloadrustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.tar.xz
rustc-698f8c2f01ea549d77d7dc3338a12e04c11057b9.zip
Adding upstream version 1.64.0+dfsg1.upstream/1.64.0+dfsg1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src')
-rw-r--r--src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs47
1 files changed, 47 insertions, 0 deletions
diff --git a/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs b/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs
new file mode 100644
index 000000000..fc22cbc5e
--- /dev/null
+++ b/src/doc/book/listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs
@@ -0,0 +1,47 @@
+use rand::Rng;
+use std::cmp::Ordering;
+use std::io;
+
+fn main() {
+ println!("Guess the number!");
+
+ let secret_number = rand::thread_rng().gen_range(1..=100);
+
+ // ANCHOR: here
+ loop {
+ // --snip--
+
+ // ANCHOR_END: here
+ println!("Please input your guess.");
+
+ let mut guess = String::new();
+
+ io::stdin()
+ .read_line(&mut guess)
+ .expect("Failed to read line");
+
+ // ANCHOR: here
+ let guess: i32 = match guess.trim().parse() {
+ Ok(num) => num,
+ Err(_) => continue,
+ };
+
+ if guess < 1 || guess > 100 {
+ println!("The secret number will be between 1 and 100.");
+ continue;
+ }
+
+ match guess.cmp(&secret_number) {
+ // --snip--
+ // ANCHOR_END: here
+ Ordering::Less => println!("Too small!"),
+ Ordering::Greater => println!("Too big!"),
+ Ordering::Equal => {
+ println!("You win!");
+ break;
+ }
+ }
+ // ANCHOR: here
+ }
+ // ANCHOR_END: here
+}