[RUST/RAND] ThreadRng 구조체 : gen_range 메소드를 사용해 숫자 맞추기 게임 만들기
■ ThreadRng 구조체의 gen_range 메소드를 사용해 임의의 난수를 생성하고 숫자를 맞추는 게임을 만드는 방법을 보여준다. ▶ Cargo.toml
1 2 3 4 5 6 7 8 9 |
[package] name = "test_project" version = "0.1.0" edition = "2021" [dependencies] rand = "0.8.0" |
▶ src/main.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
use std::cmp; use std::io; use rand; use rand::rngs; use rand::Rng; fn main() { println!("Guess the number!"); let mut thread_rng: rngs::ThreadRng = rand::thread_rng(); let secret_number : u32 = thread_rng.gen_range(1..=100); loop { println!("Please input your guess."); let mut guess_string : String = String::new(); io::stdin().read_line(&mut guess_string).expect("Failed to read line"); let guess_number : u32 = match guess_string.trim().parse() { Ok(number) => number, Err(_) => continue }; println!("You guessed : {}", guess_number); match guess_number.cmp(&secret_number) { cmp::Ordering::Less => println!("Too small!"), cmp::Ordering::Greater => println!("Too big!"), cmp::Ordering::Equal => { println!("You win!"); break; } } } } |
test_project.zip