Rust 实践指南

《Rust 实践指南》是 Rust 程序设计语言(Rust 2018 简体中文版文档)的简要实例示例集合:展示了在 Rust 生态系统中,使用各类 crate 来完成常见编程任务的良好实践。

了解更多关于《Rust 实践指南》一书的信息,请阅读关于本书,包括:如何阅读本书的提示、如何使用实例示例,以及关于注释的约定。

注:《Rust 实践指南》计划为两个阶段。
第一个阶段:经仔细斟酌,形成专业、通俗、容易理解的 Rust 生态实践指南中文版本;
第二个阶段:对书中代码进行详细讲解,在实际应用场景中对 Rust 生态 crate 进行分析、比较,以及拓展。

做贡献

《Rust 实践指南》的目的是让 Rust 程序员新手能够更容易地参与到 Rust 社区中,因此它需要——并欢迎——你做出自己力所能及的贡献。

构建和测试

首先,从 git 克隆《Rust 实践指南》并进入目录:

git clone https://github.com/zzy/rust-cookbook-zh-cn.git
cd rust-cookbook-zh-cn

《Rust 实践指南》使用 mdBook中文文档)构建,所以需要通过 Cargo中文文档)安装它:

cargo install --version 0.3.5 mdbook

若要在本地生成和阅读《Rust 实践指南》,请运行:

mdbook serve

然后在浏览器中打开 http://localhost:3000,即可阅读本书。对源代码所做的任何更改都将自动重新生成页面,并会主动刷新浏览器,因此在编辑源码时打开浏览器窗口是很有帮助的。

书中的所有实例都是使用 skeptic 测试的,它是测试任意 markdown 文档的工具,风格类似于 rustdoc。

提交前,请对整个仓库进行测试:

cargo test

祝你学习愉快,欢迎提交问题,欢迎发送 PR。

算法

实例名称Crates类别
生成随机数rand-badgecat-science-badge
生成范围内随机数rand-badgecat-science-badge
生成给定分布随机数rand-badge rand_distr-badgecat-science-badge
生成自定义类型随机值rand-badgecat-science-badge
从一组字母数字字符创建随机密码rand-badgecat-os-badge
从一组用户定义字符创建随机密码rand-badgecat-os-badge
整数 Vector 排序std-badgecat-science-badge
浮点数 Vector 排序std-badgecat-science-badge
结构体 Vector 排序std-badgecat-science-badge

命令行

实例名称Crates类别
解析命令行参数clap-badgecat-command-line-badge
ANSI 终端ansi_term-badgecat-command-line-badge

压缩

实例名称Crates类别
解压 tar 包flate2-badge tar-badgecat-compression-badge
压缩目录为 tar 包flate2-badge tar-badgecat-compression-badge
从路径移除前缀时,解压 tar 包flate2-badge tar-badgecat-compression-badge

并发/并行

实例名称Crates类别
生成短期线程crossbeam-badgecat-concurrency-badge
创建并发的数据管道crossbeam-badgecat-concurrency-badge
在两个线程间传递数据crossbeam-badgecat-concurrency-badge
保持全局可变状态lazy_static-badgecat-rust-patterns-badge
对所有 iso 文件的 SHA256 值并发求和threadpool-badge walkdir-badge num_cpus-badge ring-badgecat-concurrency-badgecat-filesystem-badge
将绘制分形的线程分派到线程池threadpool-badge num-badge num_cpus-badge image-badgecat-concurrency-badgecat-science-badgecat-rendering-badge
并行改变数组中元素rayon-badgecat-concurrency-badge
并行测试集合中任意或所有的元素是否匹配指定断言rayon-badgecat-concurrency-badge
使用指定断言并行搜索项rayon-badgecat-concurrency-badge
对 vector 并行排序rayon-badge rand-badgecat-concurrency-badge
Map-reduce 并行计算rayon-badgecat-concurrency-badge
并行生成 jpg 缩略图rayon-badge glob-badge image-badgecat-concurrency-badgecat-filesystem-badge

密码学

实例名称Crates类别
计算文件的 SHA-256 摘要ring-badge data-encoding-badgecat-cryptography-badge
使用 HMAC 摘要对消息进行签名和验证ring-badgecat-cryptography-badge
使用 PBKDF2 对密码进行加密(salt)和散列(hash)运算ring-badge data-encoding-badgecat-cryptography-badge

数据结构

实例名称Crates类别
定义并操作位域风格的类型bitflags-badgecat-no-std-badge

数据库

实例名称Crates类别
创建 SQLite 数据库rusqlite-badgecat-database-badge
数据插入和查询rusqlite-badgecat-database-badge
事务处理rusqlite-badgecat-database-badge
Postgres 数据库中创建表postgres-badgecat-database-badge
数据插入和查询postgres-badgecat-database-badge
数据聚合postgres-badgecat-database-badge

日期及时间

实例名称Crates类别
测量运行时间std-badgecat-time-badge
执行日期检查和时间计算chrono-badgecat-date-and-time-badge
时间的时区转换chrono-badgecat-date-and-time-badge
检查日期和时间chrono-badgecat-date-and-time-badge
日期和 UNIX 时间戳的互相转换chrono-badgecat-date-and-time-badge
日期和时间的格式化显示chrono-badgecat-date-and-time-badge
将字符串解析为 DateTime 结构体chrono-badgecat-date-and-time-badge

开发工具

调试工具

实例名称Crates类别
记录调试信息到控制台log-badge env_logger-badgecat-debugging-badge
记录错误信息到控制台log-badge env_logger-badgecat-debugging-badge
记录信息时,用标准输出 stdout 替换标准错误 stderrlog-badge env_logger-badgecat-debugging-badge
使用自定义日志记录器记录信息log-badgecat-debugging-badge
记录到 Unix 系统日志log-badge syslog-badgecat-debugging-badge
启用每个模块的日志级别log-badge env_logger-badgecat-debugging-badge
用自定义环境变量设置日志记录log-badge env_logger-badgecat-debugging-badge
在日志信息中包含时间戳log-badge env_logger-badge chrono-badgecat-debugging-badge
将信息记录到自定义位置log-badge log4rs-badgecat-debugging-badge

版本控制

实例名称Crates类别
解析并递增版本字符串semver-badgecat-config-badge
解析复杂的版本字符串semver-badgecat-config-badge
检查给定版本是否为预发布版本semver-badgecat-config-badge
查询适配给定范围的最新版本semver-badgecat-config-badge
检查外部命令的版本兼容性semver-badgecat-text-processing-badge cat-os-badge

构建时

实例名称Crates类别
编译并静态链接到绑定的 C 语言库cc-badgecat-development-tools-badge
编译并静态链接到绑定的 C++ 语言库cc-badgecat-development-tools-badge
编译 C 语言库时自定义设置cc-badgecat-development-tools-badge

编码

实例名称Crates类别
百分比编码(URL 编码)字符串percent-encoding-badgecat-encoding-badge
将字符串编码为 application/x-www-form-urlencodedurl-badgecat-encoding-badge
编码和解码十六进制data-encoding-badgecat-encoding-badge
编码和解码 base64base64-badgecat-encoding-badge
读取 CSV 记录csv-badgecat-encoding-badge
读取有不同分隔符的 CSV 记录csv-badgecat-encoding-badge
筛选匹配断言的 CSV 记录csv-badgecat-encoding-badge
用 Serde 处理无效的 CSV 数据csv-badge serde-badgecat-encoding-badge
将记录序列化为 CSVcsv-badgecat-encoding-badge
用 Serde 将记录序列化为 CSVcsv-badge serde-badgecat-encoding-badge
转换 CSV 文件的列csv-badge serde-badgecat-encoding-badge
将非结构化 JSON 序列化和反序列化serde-json-badgecat-encoding-badge
反序列化 TOML 配置文件toml-badgecat-encoding-badge
以小端模式(低位模式)字节顺序读写整数byteorder-badgecat-encoding-badge

错误处理

实例名称Crates类别
在 main 方法中对错误适当处理error-chain-badgecat-rust-patterns-badge
避免在错误转变过程中遗漏错误error-chain-badgecat-rust-patterns-badge
获取复杂错误场景的回溯error-chain-badgecat-rust-patterns-badge

文件系统

实例名称Crates类别
Read lines of strings from a filestd-badgecat-filesystem-badge
Avoid writing and reading from a same filesame_file-badgecat-filesystem-badge
Access a file randomly using a memory mapmemmap-badgecat-filesystem-badge
File names that have been modified in the last 24 hoursstd-badgecat-filesystem-badge cat-os-badge
Find loops for a given pathsame_file-badgecat-filesystem-badge
Recursively find duplicate file nameswalkdir-badgecat-filesystem-badge
Recursively find all files with given predicatewalkdir-badgecat-filesystem-badge
Traverse directories while skipping dotfileswalkdir-badgecat-filesystem-badge
Recursively calculate file sizes at given depthwalkdir-badgecat-filesystem-badge
Find all png files recursivelyglob-badgecat-filesystem-badge
Find all files with given pattern ignoring filename caseglob-badgecat-filesystem-badge

硬件支持

实例名称Crates类别
Check number of logical cpu coresnum_cpus-badgecat-hardware-support-badge

内存管理

实例名称Crates类别
Declare lazily evaluated constantlazy_static-badgecat-caching-badge cat-rust-patterns-badge

网络

实例名称Crates类别
Listen on unused port TCP/IPstd-badgecat-net-badge

操作系统

实例名称Crates类别
Run an external command and process stdoutregex-badgecat-os-badge cat-text-processing-badge
Run an external command passing it stdin and check for an error coderegex-badgecat-os-badge cat-text-processing-badge
Run piped external commandsstd-badgecat-os-badge
Redirect both stdout and stderr of child process to the same filestd-badgecat-os-badge
Continuously process child process’ outputsstd-badgecat-os-badgecat-text-processing-badge
Read environment variablestd-badgecat-os-badge

科学计算

数学

实例名称Crates类别
Vector Normndarray-badgecat-science-badge
Adding matricesndarray-badgecat-science-badge
Multiplying matricesndarray-badgecat-science-badge
Multiply a scalar with a vector with a matrixndarray-badgecat-science-badge
Invert matrixnalgebra-badgecat-science-badge
Calculating the side length of a trianglestd-badgecat-science-badge
Verifying tan is equal to sin divided by cosstd-badgecat-science-badge
Distance between two points on the Earthstd-badgecat-science-badge
Creating complex numbersnum-badgecat-science-badge
Adding complex numbersnum-badgecat-science-badge
Mathematical functions on complex numbersnum-badgecat-science-badge
Measures of central tendencystd-badgecat-science-badge
Computing standard deviationstd-badgecat-science-badge
Big integersnum-badgecat-science-badge

文本处理

实例名称Crates类别
Collect Unicode Graphemesunicode-segmentation-badgecat-encoding-badge
Verify and extract login from an email addressregex-badge lazy_static-badgecat-text-processing-badge
Extract a list of unique #Hashtags from a textregex-badge lazy_static-badgecat-text-processing-badge
Extract phone numbers from textregex-badgecat-text-processing-badge
Filter a log file by matching multiple regular expressionsregex-badgecat-text-processing-badge
Replace all occurrences of one text pattern with another pattern.regex-badge lazy_static-badgecat-text-processing-badge
Implement the FromStr trait for a custom structstd-badgecat-text-processing-badge

Web 编程

Scraping Web Pages

实例名称Crates类别
Extract all links from a webpage HTMLreqwest-badge select-badgecat-net-badge
Check webpage for broken linksreqwest-badge select-badge url-badgecat-net-badge
Extract all unique links from a MediaWiki markupreqwest-badge regex-badgecat-net-badge

Uniform Resource Locations (URL)

实例名称Crates类别
Parse a URL from a string to a Url typeurl-badgecat-net-badge
Create a base URL by removing path segmentsurl-badgecat-net-badge
Create new URLs from a base URLurl-badgecat-net-badge
Extract the URL origin (scheme / host / port)url-badgecat-net-badge
Remove fragment identifiers and query pairs from a URLurl-badgecat-net-badge

Media Types (MIME)

实例名称Crates类别
Get MIME type from stringmime-badgecat-encoding-badge
Get MIME type from filenamemime-badgecat-encoding-badge
Parse the MIME type of a HTTP responsemime-badge reqwest-badgecat-net-badge cat-encoding-badge

Clients

实例名称Crates类别
Make a HTTP GET requestreqwest-badgecat-net-badge
Query the GitHub APIreqwest-badge serde-badgecat-net-badge cat-encoding-badge
Check if an API resource existsreqwest-badgecat-net-badge
Create and delete Gist with GitHub APIreqwest-badge serde-badgecat-net-badge cat-encoding-badge
Consume a paginated RESTful APIreqwest-badge serde-badgecat-net-badge cat-encoding-badge
Download a file to a temporary directoryreqwest-badge tempdir-badgecat-net-badge cat-filesystem-badge
Make a partial download with HTTP range headersreqwest-badgecat-net-badge
POST a file to paste-rsreqwest-badgecat-net-badge