美文网首页
Rust 编程语言-2-猜字谜游戏

Rust 编程语言-2-猜字谜游戏

作者: onemoremile | 来源:发表于2022-01-06 07:48 被阅读0次

猜字谜的游戏 (全书第一个代码实例)

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..101);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        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);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}
  • 如何从控制台读取输入
  • expect()对异常的处理
  • rand 随机数生成
  • match模式匹配
  • continue,break
  • loop的使用

相关文章

网友评论

      本文标题:Rust 编程语言-2-猜字谜游戏

      本文链接:https://www.haomeiwen.com/subject/lbokcrtx.html