Mercurial > hg > Members > kono > rust-tutorial
changeset 3:9bb0201e638b
guessing complete
author | Shinji KONO <kono@ie.u-ryukyu.ac.jp> |
---|---|
date | Mon, 11 Jan 2021 19:17:21 +0900 |
parents | d2f0d33c1586 |
children | 3d23e8517403 |
files | src/t01guessing/Cargo.toml src/t01guessing/src/main.rs |
diffstat | 2 files changed, 30 insertions(+), 7 deletions(-) [+] |
line wrap: on
line diff
--- a/src/t01guessing/Cargo.toml Mon Jan 11 16:27:48 2021 +0900 +++ b/src/t01guessing/Cargo.toml Mon Jan 11 19:17:21 2021 +0900 @@ -7,3 +7,4 @@ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +rand = "0.5.5" \ No newline at end of file
--- a/src/t01guessing/src/main.rs Mon Jan 11 16:27:48 2021 +0900 +++ b/src/t01guessing/src/main.rs Mon Jan 11 19:17:21 2021 +0900 @@ -1,15 +1,37 @@ use std::io; +use rand::Rng; + +use std::cmp::Ordering; fn main() { println!("Guess the number!"); - println!("Please input your guess."); + let secret_number = rand::thread_rng().gen_range(1, 101); + + println!("The secret number is: {}", secret_number); - let mut guess = String::new(); + loop { + println!("Please input your guess."); + + let mut guess = String::new(); + + io::stdin() + .read_line(&mut guess) + .expect("Failed to read line"); - io::stdin() - .read_line(&mut guess) - .expect("Failed to read line"); + let guess: u32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + println!("You guessed: {}", guess); - println!("You guessed: {}", guess); -} + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + } +} \ No newline at end of file