Last active
January 13, 2022 01:12
-
-
Save topherPedersen/20952b302cf6eaf2c76ae1c4b4cfa19e to your computer and use it in GitHub Desktop.
Number Guessing Game in Rust (From the Official Rust Lang Book)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use rand::Rng; | |
| use std::cmp::Ordering; | |
| use std::io; | |
| fn main() { | |
| loop { | |
| let secret_number = rand::thread_rng().gen_range(1..101); | |
| println!("Guess the number"); | |
| println!("Please input your guess."); | |
| let mut guess = String::new(); | |
| io::stdin() | |
| .read_line(&mut guess) | |
| .expect("Failed to read line"); | |
| // let guess: u32 = guess.trim().parse().expect("Please type a number!"); | |
| let guess: u32 = match guess.trim().parse() { | |
| Ok(num) => num, | |
| Err(_) => continue, | |
| }; | |
| match guess.cmp(&secret_number) { | |
| Ordering::Less => println!("Too small!"), | |
| Ordering::Greater => println!("Too big!"), | |
| Ordering::Equal => { | |
| println!("You win!"); | |
| break; // exit loop | |
| } | |
| } | |
| println!("The number was: {}", secret_number); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment