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

本笔记为了记录学习Rust过程,内容如有错误请大佬指教

使用IDE:vs code

参考教程:菜鸟教程链接: 菜鸟教程链接:

参考文档:《Rust程序设计语言》Rust 官方文档中文教程

编写猜数字游戏

创建项目文件

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

rust 复制代码
cargo new guessing_game
cd guessing_game

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

处理用户输入数据

rust教程中通过一个简单的处理输入数据的例子来告诉我们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);
}

上述代码编译运行后的结果如下:

引入crate库

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

rust 复制代码
[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"
$ 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

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

rust 复制代码
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;
            }
        }
    }
    
}
$ 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!!!

猜数字小游戏最终版

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

rust 复制代码
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;
            }
        }
    }
}
$ 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!!!
相关推荐
eybk3 小时前
Pytorch+Mumu模拟器+萤石摄像头实现对小孩学习的监控
学习
6.943 小时前
Scala学习记录 递归调用 练习
开发语言·学习·scala
守护者1705 小时前
JAVA学习-练习试用Java实现“使用Arrays.toString方法将数组转换为字符串并打印出来”
java·学习
学会沉淀。5 小时前
Docker学习
java·开发语言·学习
Rinai_R5 小时前
计算机组成原理的学习笔记(7)-- 存储器·其二 容量扩展/多模块存储系统/外存/Cache/虚拟存储器
笔记·物联网·学习
吃着火锅x唱着歌5 小时前
PHP7内核剖析 学习笔记 第四章 内存管理(1)
android·笔记·学习
ragnwang5 小时前
C++ Eigen常见的高级用法 [学习笔记]
c++·笔记·学习
唐 城6 小时前
curl 放弃对 Hyper Rust HTTP 后端的支持
开发语言·http·rust
Web阿成7 小时前
3.学习webpack配置 尝试打包ts文件
前端·学习·webpack·typescript