如何用 Cargo 管理 Rust 工程系列 戊

以下内容为本人的学习笔记,如需要转载,请声明原文链接微信公众号「ENG八戒」mp.weixin.qq.com/s/-OiWtUCUc...

单元和集成测试

Rust 为单元测试提供了非常好的原生支持。

创建库工程时,cargo 生成的源码文件 lib.rs 自带了示例代码,而且包含测试函数,看看代码

rust 复制代码
$ cat lib_rust/src/lib.rs 
pub fn add(left: usize, right: usize) -> usize {
    left + right
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let result = add(2, 2);
        assert_eq!(result, 4);
    }
}

函数 add 实现两数求和,测试函数的 it_works 实现对函数 add 的测试。

cargo 提供了 test 指令启动单元测试

bash 复制代码
$ cd lib_rust
$ cargo test
   Compiling lib_rust v0.1.0 (~/lib_rust)
    Finished test [unoptimized + debuginfo] target(s) in 1.67s
     Running unittests src/lib.rs (target/debug/deps/lib_rust-996ac7b1e383793c)

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests lib_rust

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

测试过程反映了每个测试函数的结果,以及汇总。

Cargo 运行的背后

看完上面的内容,不禁想问每次运行 cargo 指令时,它到底在干什么?

执行 cargo 指令时加上 -v 选项,可以把执行过程的详细信息打印出来。那么,来看看 cargo 清理中间文件和重新执行编译构建的详细过程

scss 复制代码
$ cd hello_rust/
$ cargo clean -v
    Removing ~/hello_rust/target
$ cargo build -v
   Compiling hello_rust v0.1.0 (~/hello_rust)
     Running `~/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/bin/rustc --crate-name hello_rust --edition=2021 src/main.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --diagnostic-width=89 --crate-type bin --emit=dep-info,link -C embed-bitcode=no -C debuginfo=2 -C metadata=60af8441ea417b4f -C extra-filename=-60af8441ea417b4f --out-dir ~/hello_rust/target/debug/deps -C incremental=~/hello_rust/target/debug/incremental -L dependency=~/hello_rust/target/debug/deps`
    Finished dev [unoptimized + debuginfo] target(s) in 0.83s

可见,cargo 其实是一个包装器(wrapper),在执行编译构建时调用编译器 rustc,清理中间文件就是直接删掉文件夹 target。

编译第三方 Rust 包

目前为止,上面提到的技巧都以自建工程包为基础,但是也可以运用在从网上获取到的 Rust crate(包)。对待这些第三方包,就是下载下来,或者用 git 克隆它的仓库代码到本地,然后进入包文件夹并启动构建

bash 复制代码
git clone <xxx>
cd <package-folder>
cargo build

more

关于更多的 cargo 用法,可以查看帮助

shell 复制代码
$ cargo --help

本文目标是简单介绍一般开发流程里会用到的 Cargo 构建技巧,尝试抛砖引玉,帮助 rust 初学者上手工具 cargo 的使用,不旨在面面俱到,如果你对 cargo 特别感兴趣还可以去看看《cargo book》。

本系列文章已结束,谢谢各位读者朋友的支持...

相关推荐
程工造Agent17 小时前
从 0 到 1 学 Codex 源码:顺着 main 读懂 Rust 闭包与 async move
rust·ai编程
shimly1234561 天前
(done) RUST 指针详解
rust
geovindu1 天前
rust: Template Method Pattern
开发语言·后端·设计模式·rust·行为模式·模板方法模
遇码1 天前
Rust 桌面应用自托管自动更新:latest.json 清单 + minisign 签名校验的完整做法
人工智能·ai·rust·大模型·agent
geovindu1 天前
rust: Template Method Pattern(续)
开发语言·后端·设计模式·rust·行为模式·板方法模式
niyongsheng2 天前
多智能体连续时间内路径规划:AA-SIPP(m) 的 Rust 实现与算法
算法·rust·机器人
NetX行者2 天前
Rust 初体验:一个全栈工程师的编译器“毒打“笔记
开发语言·笔记·rust
Amos_Web2 天前
Rspack 源码解析(二十七):AsyncWasmParserAndGenerator 如何把二进制变成异步模块
前端·rust
敲代码的玉米C2 天前
菜单栏做出来了,内存预算却没过:Hostwatch 开发手记(二)
rust
敲代码的玉米C2 天前
电脑卡了,然后呢?我想用 Rust 做一个 Mac 诊断小工具
rust