cargo 工具的使用详解 ---从cargo开始规范代码
cago命令参数
cargo --list Installed Commands: add Add dependencies to a Cargo.toml manifest file b alias: build bench Execute all benchmarks of a local package build Compile a local package and all of its dependencies c alias: check check Check a local package and all of its dependencies for errors clean Remove artifacts that cargo has generated in the past clippy Checks a package to catch common mistakes and improve your Rust code. config Inspect configuration values d alias: doc doc Build a package's documentation fetch Fetch dependencies of a package from the network fix Automatically fix lint warnings reported by rustc fmt Formats all bin and lib files of the current crate using rustfmt. generate-lockfile Generate the lockfile for a package git-checkout This command has been removed help Displays help for a cargo subcommand info Display information about a package in the registry init Create a new cargo package in an existing directory install Install a Rust binary locate-project Print a JSON representation of a Cargo.toml file's location login Log in to a registry. logout Remove an API token from the registry locally metadata Output the resolved dependencies of a package, the concrete used versions including overrides, in machine-readable format miri new Create a new cargo package at <path> owner Manage the owners of a crate on the registry package Assemble the local package into a distributable tarball pkgid Print a fully qualified package specification publish Upload a package to the registry r alias: run read-manifest Print a JSON representation of a Cargo.toml manifest. remove Remove dependencies from a Cargo.toml manifest file report Generate and display various kinds of reports rm alias: remove run Run a binary or example of the local package rustc Compile a package, and pass extra options to the compiler rustdoc Build a package's documentation, using specified custom flags. search Search packages in the registry. Default registry is crates.io t alias: test test Execute all unit and integration tests and build examples of a local package tree Display a tree visualization of a dependency graph uninstall Remove a Rust binary update Update dependencies as recorded in the local lock file vendor Vendor all dependencies for a project locally verify-project Check correctness of crate manifest version Show version information yank Remove a pushed crate from the index
以下是对 Cargo 工具参数用法 的总结,根据其主要功能进行分类:
1. 项目管理相关
-
new
创建一个新项目(cargo new <project_name>
)。
示例:cargo new my_project --bin # 创建一个二进制项目 cargo new my_library --lib # 创建一个库项目 -
init
在现有目录中初始化 Cargo 项目(cargo init
)。
示例:cargo init --bin # 初始化为二进制项目 -
locate-project
打印当前目录中 Cargo 项目的Cargo.toml
文件位置。
示例:cargo locate-project -
verify-project
检查Cargo.toml
的正确性,确保项目配置无误。
示例:cargo verify-project
2. 依赖管理
-
add
向Cargo.toml
中添加依赖。
示例:cargo add serde # 添加 serde 依赖 cargo add tokio --features full # 添加 tokio 依赖,并启用 `full` 特性 -
remove
/rm
从Cargo.toml
中移除依赖。
示例:cargo rm serde -
update
根据Cargo.toml
文件更新Cargo.lock
中的依赖版本。
示例:cargo update -
fetch
下载依赖但不编译,用于预加载依赖。
示例:cargo fetch -
vendor
将项目的所有依赖存储到本地vendor/
目录,用于离线构建。
示例:cargo vendor -
generate-lockfile
手动生成Cargo.lock
文件,而不需要编译代码。 Cargo.lock 是 Rust 项目中的一个文件,它记录了项目依赖的具体版本和相关元数据。当你使用 cargo build、cargo run 或其他命令时,Cargo 会使用这个文件来确定使用哪些具体版本的依赖包。
示例:cargo generate-lockfile
3. 构建与运行
-
build
/b
编译当前项目及其依赖。
示例:cargo build --release # 以发布模式构建 -
check
/c
检查项目是否存在错误,但不实际生成二进制文件。
示例:cargo check -
run
/r
构建并运行项目的二进制文件。
示例:cargo run -- <arguments> # 向程序传递命令行参数
4. 文档生成
这要求我们先写代码,在写文档,是一种已代码实践为中心的编程设计思维。
doc
/d
构建文档。
示例:cargo doc --open # 构建并在浏览器中打开文档
cargo可以将代码中的结构和注释生成代码阅读文档,让使用着更加容易上手!
注释中///和//!的区别:
特性 | /// | //! |
---|---|---|
作用范围 | 单个代码项(函数、结构体、枚举等) | 当前模块或整个 crate |
用途 | 为具体的代码项提供详细说明和使用示例 | 为模块或 crate 提供整体性描述和使用上下文 |
位置 | 放在被注释项的上方 | 放在模块或 crate 的顶部 |
常见用途 | 描述函数的功能、参数、返回值;描述结构体的字段等 | 描述模块的整体功能;描述 crate 的用途和包含的模块等 |
生成文档中的展示 | 具体项的文档页中显示 | 模块或 crate 的主页中显示 |
rustdoc
使用指定的标志生成文档。
示例:cargo rustdoc -- --cfg feature="docs" # 定制化生成文档
doc和rustdoc的区别:
功能 | cargo doc | cargo rustdoc |
---|---|---|
默认生成文档 | ✅ | ✅ |
支持自定义 rustdoc 标志 | ❌ | ✅ |
控制细节与条件编译 | ❌ | ✅ |
简单总结:
如果你只需要生成普通文档,用 cargo doc 即可。
如果需要更复杂的控制或调试文档生成,则使用 cargo rustdoc。例如,仅为某些特性生成文档,或处理条件编译代码块。例如生成 JSON 格式文档以供其他工具使用。
5. 测试与基准测试
test
/t
运行单元测试和集成测试。
示例:cargo test # 运行所有测试 cargo test my_test # 运行特定测试
cargo 可识别的test分为单测和集成测试,
- 单元测试目录在代码同一文件中,用#[cfg(test)]标识,示例:
#[cfg(test)] // 测试模块仅在运行测试时编译 mod tests { use super::*; // 导入当前模块的代码 #[test] // 表示这是一个测试函数 fn test_add() { assert_eq!(add(2, 3), 5); // 检查表达式是否相等 } #[test] fn test_add_negative() { assert_eq!(add(-2, -3), -5); } } ///assert!(condition):当条件为 false 时,测试失败。 ///assert_eq!(a, b):当 a 和 b 不相等时,测试失败。 ///assert_ne!(a, b):当 a 和 b 相等时,测试失败。 ///panic!():手动触发失败,用于特定条件下。
- 集成测试在src同一级目录中,使用use导入库,测试库的所有公共接口
///your_project/ ///├── Cargo.toml ///├── src/ ///│ └── lib.rs ///└── tests/ /// └── integration_test.rs // tests/integration_test.rs use your_project_name; // 导入库,项目名在 Cargo.toml 中指定 #[test] fn test_add() { assert_eq!(your_project_name::add(2, 3), 5); }
覆盖率这里需要下载cargo提供的工具,cargo-llvm-cov或者grcov ,另行了解
bench
运行基准测试(需要启用bench
功能)。 这里的bench运行需要criterion 依赖,并且编写bench的代码。
示例:cargo bench
6. 清理与格式化
-
clean
清除之前生成的构建产物。
示例:cargo clean -
fmt
使用rustfmt
格式化代码,保持官方风格一致性。
示例:cargo fmt -
fix
自动修复代码中的常见问题(如编译警告)。可以结合clippy报告使用, clippy 是 Rust 的一个工具,专门用于发现代码中的潜在问题(例如性能优化、可能的错误或代码风格问题)
示例:cargo fix --allow-dirty
7. 发布与注册
这里的publish、login、yank与发布到官方库有关。
-
publish
将包上传到注册表(如crates.io
)。
示例:cargo publish -
package
将包打包为.crate
文件(但不发布)。
示例:cargo package -
login
/logout
登录或注销注册表账户。
示例:cargo login <API-TOKEN> cargo logout -
yank
从注册表中移除发布的 crate。
示例:cargo yank --vers 1.0.0
8. 调试与信息
-
clippy
使用clippy
检查代码潜在问题和改进建议。
示例:cargo clippy --fix # 自动修复可修复的问题 -
tree
显示项目依赖的层次结构。
示例:cargo tree -
metadata
输出项目的元数据(如依赖树)。
示例:cargo metadata --format-version 1 -
info
显示注册表中包的信息。
示例:cargo info serde
9. 其他辅助命令
-
help
查看命令帮助。
示例:cargo help build -
version
显示 Cargo 版本信息。
示例:cargo version
总结
Cargo 的命令全面涵盖了 Rust 项目生命周期的各个方面:
- 创建与管理项目:
new
、init
、verify-project
- 添加与移除依赖:
add
、remove
、update
- 构建与运行项目:
build
、check
、run
- 测试与基准测试:
test
、bench
- 文档生成与格式化:
doc
、fmt
- 发布与注册:
publish
、package
、yank
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!