• 【Rust学习】《Rust程序设计语言》第二章:编写猜数字游戏


    本笔记为了记录学习Rust过程,内容如有错误请大佬指教
    使用IDE:vs code
    参考教程:菜鸟教程链接: 菜鸟教程链接:
    参考文档:《Rust程序设计语言》Rust 官方文档中文教程

    创建项目文件

    在这里我们用之前学习到的Cargo来构建我们的项目,具体代码如下

    cargo new guessing_game
    cd guessing_game
    
    • 1
    • 2

    在这里插入图片描述
    可以看到我在上面还执行了一遍cargo run命令,运行结果是Hello, world! 这是因为cargo new命令在创建文件的时候会默认生成一个Hello, world! 程序。我们可以在项目的src/main.rs 目录下的文件查看。
    在这里插入图片描述

    处理用户输入数据

    rust教程中通过一个简单的处理输入数据的例子来告诉我们rust中关于引用 标准库 初始化变量 错误处理等特性,详细的内容可以去参考《Rust程序设计语言》,我这里就简单写了一遍给出的代码。

    use std::io;
    
    fn main() {
        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");
        
        println!("You guessed: {}", guess);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    上述代码编译运行后的结果如下:
    在这里插入图片描述

    引入crate库

    crate 是一个 Rust 代码包,我们现在需要在项目中添加外部的库crate rand 。我们需要修改Cargo.toml 文件,引入一个 rand 依赖。如下所示,将rand = “0.8.3” 添加到 [dependencies] 表块标题下。然后输入 cargo build构建项目。

    [package]
    name = "guessing_game"
    version = "0.1.0"
    edition = "2021"
    
    # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
    
    [dependencies]
    rand = "0.8.3"
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    $ cargo build
        Updating crates.io index
      Downloaded cfg-if v1.0.0
      Downloaded getrandom v0.2.14
      Downloaded rand_chacha v0.3.1
      Downloaded rand_core v0.6.4
      Downloaded ppv-lite86 v0.2.17
      Downloaded rand v0.8.5
      Downloaded 6 crates (192.5 KB) in 15.17s
       Compiling cfg-if v1.0.0
       Compiling ppv-lite86 v0.2.17
       Compiling getrandom v0.2.14
       Compiling rand_core v0.6.4
       Compiling rand_chacha v0.3.1
       Compiling rand v0.8.5
       Compiling guessing_game v0.1.0 (D:\Rust\test\guessing_game)
        Finished dev [unoptimized + debuginfo] target(s) in 19.66s
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    完善好第一版的代码后,我得到了一个建议的猜数字游戏。

    use std::io;
    use std::cmp::Ordering;
    use rand::Rng;
    fn main() {
        println!("Guess the number!");
    
        let secret_number = rand::thread_rng().gen_range(1..101);
    
        println!("The secret_number is: {}", secret_number);
    
        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 = guess.trim().parse().expect("Please type a number!");//遮蔽变量guess,使得下面代码编译不会出错
        
            println!("You guessed: {}", guess);
    
            match guess.cmp(&secret_number){//使用表达式来输出比较的结果
                Ordering::Less => println!("Too small!"),
                Ordering::Greater => println!("Too big!"),
                Ordering::Equal => {
                    println!("Bingo!!!");
                    break;
                }
            }
        }
        
    }
    
    
    • 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
    $ cargo run
       Compiling guessing_game v0.1.0 (D:\Rust\test\guessing_game)
        Finished dev [unoptimized + debuginfo] target(s) in 0.44s
         Running `target\debug\guessing_game.exe`
    Guess the number!
    The secret_number is: 78
    Please input your guess.
    1
    You guessed: 1
    Too small!
    Please input your guess.
    2
    You guessed: 2
    Too small!
    Please input your guess.
    70
    You guessed: 70
    Too small!
    Please input your guess.
    100
    You guessed: 100
    Too big!
    Please input your guess.
    78
    You guessed: 78
    Bingo!!!
    
    • 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

    猜数字小游戏最终版

    最终版本加入了过滤非数字输入的功能,详细实现可以参考书中的步骤进行复现,我就直接附上代码和我的结果啦!

    use std::io;
    use std::cmp::Ordering;
    use rand::Rng;
    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!("Bingo!!!");
                    break;
                }
            }
        }
    }
    
    • 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
    $ cargo run
       Compiling guessing_game v0.1.0 (D:\Rust\test\guessing_game)
        Finished dev [unoptimized + debuginfo] target(s) in 1.11s
         Running `target\debug\guessing_game.exe`
    Guess the number!
    Please input your guess.
    50
    You guessed: 50
    Too big!
    Please input your guess.
    25
    You guessed: 25
    Too big!
    Please input your guess.
    12
    You guessed: 12
    Too small!
    Please input your guess.
    15
    You guessed: 15
    Bingo!!!
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
  • 相关阅读:
    hadoop组成
    virtualbox虚拟机安装在笔记本上使用WIFI无法上网
    C++语言的广泛应用领域
    【YOLO系列】YOLOv1学习(PyTorch)原理加代码
    基于Python + SnowNLP实现一个文本情感分析系统
    改进YOLOv7系列:首发最新结合多种X-Transformer结构新增小目标检测层,让YOLO目标检测任务中的小目标无处遁形
    03大数据技术之Hadoop(HDFS)
    RestTemplate踩坑 之 ContentType 自动添加字符集
    NP9 十六进制数字的大小牛客网python答案(已测试通过)
    蓝桥杯每日一题(python)
  • 原文地址:https://blog.csdn.net/weixin_57171836/article/details/138196931