Cargo 是 Rust 语言的构建系统和包管理器。
和前端的 npm
一样,Rust生态使用 Cargo
进行包管理和组织代码。cargo 提供了一系列的工具,从项目的建立、构建到测试、运行直至部署,为 Rust 项目的管理提供尽可能完整的手段。
检查cargo使用安装
当我们安装rust的时候,自动安装了 Cargo
, 可以使用以下命令进行验证。
bash
cargo --version
使用Cargo创建一个项目
使用 Cargo
既可以创建二进制可执行程序项目,也可以创建一个库项目。
我们可以使用 cargo new hello_cargo
创建一个简单的项目。
其中 hello_cargo
为项目路径和名称,执行以上命令,将在当前目录的hello_cargo
文件夹生成如下的代码:
.
├── Cargo.toml
└── src
└── main.rs
如果是非git仓库目录下,还会生成初始化一个Git repository, 并生成
.gitignore
w文件。
其中Filename: Cargo.toml
的内容如下:
# 项目编译名称、版本,以及 使用的rust版本
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# 项目依赖,当前项目没有任何依赖,所以是空的
# 在 Rust 中,代码包被称为 “crates”
[dependencies]
Cargo
使用TOML
作为配置文件的格式。
同时,Cargo
会在 src目录下生成一个 main.rs 文件。
rust
# src/main.rs
fn main() {
println!("Hello, world!");
}
构建并运行Cargo项目
执行 cargo build
bash
itshizhan@BF-202109161457:/mnt/d/rust-apprentice/basic_demos/justtest$ cargo build
Compiling hello_cargo v0.1.0 (/mnt/d/rust-apprentice/basic_demos/hello_cargo)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.94s
执行完成,会生成如下文件:

即在target/debug/hello_cargo
(or target\debug\hello_cargo.exe on Windows) 下生成一个可执行文件。
默认的构建是debug
模式。如果我们运行./target/debug/hello_cargo
会输出 Hello, world!
如果你觉得每次都要先构建在执行比较麻烦,也可以使用cargo run
命令,编译并运行项目。
bash
itshizhan@BF-202109161457:/mnt/d/rust-apprentice/basic_demos/hello_cargo$ cargo run
Compiling hello_cargo v0.1.0 (/mnt/d/rust-apprentice/basic_demos/hello_cargo)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.91s
Running `target/debug/hello_cargo`
Hello, world!
如果是WSL子系统构建报错error: linker
cc not found
, 可以安装如下依赖。
bash
sudo apt update
sudo apt install build-essential
Building for Release
如果项目需要发布到生产环境,需要编译是进行优化,我们可以使用如下命令:
bash
cargo build --release
执行后,会在 target/release
目录生产可执行文件。
将普通项目转为Cargo项目
If you started a project that doesn’t use Cargo, as we did with the “Hello, world!” project, you can convert it to a project that does use Cargo. Move the project code into the src directory and create an appropriate Cargo.toml file. One easy way to get that Cargo.toml file is to run cargo init, which will create it for you automatically.
即将项目代码移动到src目录中,运行cargo init
创建一个适当的Cargo.toml文件。
Cargo 常用命令
bash
# 创建一个新的 Rust 项目,指定 [project-name] 作为项目的名称。
cargo new [project-name]
# 编译你的项目,默认情况下为 debug 模式。
cargo build
# 编译发布版本,启用优化选项。
cargo build --release
# 编译并运行你的项目。
cargo run
# 快速检查代码是否可以成功编译,但不生成二进制文件。
cargo check
# 清除目标(target)目录中的所有生成文件。
cargo clean
# 运行测试用例。
cargo test
# 运行性能基准测试。
cargo bench
# 自动格式化代码以符合 Rust 官方风格指南。
cargo fmt
# 使用 Clippy lint 工具提供额外的编译器警告和建议。
cargo clippy
# 构建项目及其所有依赖项的文档,并在浏览器中打开。
cargo doc --open
# 添加一个依赖到 Cargo.toml 文件中。(需要安装 cargo-edit 插件)
cargo add [dependency-name]
# 更新 Cargo.lock 文件中的依赖版本。
cargo update
# 将你的 crate 发布到 crates.io。
cargo publish
# 安装一个 binary crate 到本地环境中。
cargo install [crate-name]
# 卸载之前通过 cargo install 安装的 binary crate。
cargo uninstall [crate-name]