好久没写 Rust 了,参考《Rust 程序设计语言》写了一下猜数游戏。差不多 40 行,感觉写起来真舒服。
use rand::Rng;
use std::{cmp::Ordering, io};fn main() {let secret_number = rand::thread_rng().gen_range(0..100);println!("[*] Guess the number!");println!("[*] The secret number is: {}", secret_number);println!("[*] Please input your guess");let mut guess = String::new();loop {guess.clear();// 持续使用 guess 会出错,还可以把 String::new() 放在循环内。io::stdin().read_line(&mut guess).expect("[*] Failed to read line");let guess = match guess.trim().parse::<i32>() {Ok(num) => num,Err(_) => {println!("[*] Please input number!");continue;}};println!("[*] You guessed: {}", guess);match guess.cmp(&secret_number) {Ordering::Equal => {print!("Equal, You win.");break;}Ordering::Less => {println!("Less")}Ordering::Greater => {println!("Greater")}}}
}