Skip to content

常用第三方库及部分推荐

Rust 生态系统中含有丰富的三方库。

在平时的开发中都需要用到外部 crate,毕竟有很多的 crate 非常常用,我们没有必要重新实现。下面我们对几个常用的crate进行简单的使用。

rand 随机数

随机数不在标准库中。如果您需要使用该三方库,需要在Cargo.toml文件中添加依赖:

text
[package]
name = "rust_book"
version = "0.1.0"
authors = ["David MacLeod"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

现在,如果你想添加rand crate,在crates.io上搜索它,这是所有crate的去处。这将带你到https://crates.io/crates/rand。当你点击那个,你可以看到一个屏幕,上面写着Cargo.toml rand = "0.7.3"。你所要做的就是在[dependencies]下添加这样的内容:

toml
[package]
name = "hello"
version = "0.1.0"
authors = "someone"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.8.5"

然后Cargo会帮你完成剩下的工作。然后你就可以在rand文档网站上开始编写像本例代码这样的代码。要想进入文档,你可以点击crates.io上的页面中的docs按钮。

如果要使用rand,可以在代码文件中这样使用:

rust
use rand; // This means the whole crate rand
          // On your computer you can't just write this;
          // you need to write in the Cargo.toml file first

fn main() {
    for _ in 0..5 {
        let random_u16 = rand::random::<u16>();
        print!("{} ", random_u16);
    }
}

每次都会打印不同的u16号码,比如42266 52873 56528 46927 6867

rand中的主要功能是randomthread_rng(rng的意思是 "随机数发生器")。而实际上如果你看random,它说:"这只是thread_rng().gen()的一个快捷方式"。所以其实是thread_rng基本做完了一切。

下面是一个简单的例子,从1到10的数字。为了得到这些数字,我们在1到11之间使用.gen_range()

rust
use rand::{thread_rng, Rng}; // Or just use rand::*; if we are lazy

fn main() {
    let mut number_maker = thread_rng();
    for _ in 0..5 {
        print!("{} ", number_maker.gen_range(1, 11));
    }
}

serde 序列化

Serde 是一个用于高效且通用地序列化和反序列化 Rust 数据结构的框架,了解更多

最常见的使用方法是通过创建一个struct,上面有两个属性:SerializeDeserialize

rust
#[derive(Serialize, Deserialize, Debug)]
struct Point {
    x: i32,
    y: i32,
}

SerializeDeserializetrait是使转换变得简单的原因。(这也是serde这个名字的由来)如果你的结构体上有这两个trait,那么你只需要调用一个方法就可以把它转化为JSON或其他任何东西。

regex 正则表达式

这个 crate 提供了一个用于解析、编译和执行正则表达式的库,了解更多

如何识别三方库的质量

当前在Rust生态中,存在96000+库,质量上参差不齐。可以通过以下方式识别三方库的质量:

  • crate 的下载次数。
  • crate 的使用趋势,它是获得用户还是失去用户。
  • crate 的文档、示例是否可用、可靠。
  • 根据发布历史、破坏版本的数量、补丁版本和夜间功能的使用来估计稳定性。
  • 存在测试、CI、代码注释。
  • crate 元数据的准确性和完整性。
  • 作者和贡献者的数量。
  • 板条箱是否被积极维护或至少稳定并完成。