Rust Cargo完全指南:从cargo new到cargo publish,一篇搞定包管理与构建优化

AI 概述
Cargo 是 Rust 的包管理器兼构建工具,支持创建二进制 / 库项目,提供构建、运行、测试等核心命令。其核心配置文件为 Cargo.toml(定义依赖、项目信息)和 Cargo.lock(锁定依赖版本),依赖遵循语义化版本,可从 crates.io、Git 或本地引入。Cargo 支持多二进制项目、工作空间管理,内置单元 / 集成测试能力,还可优化编译速度与二进制大小,搭配 rustfmt、Clippy 等工具提升开发效率,最终能将 crate 发布至 crates。
目录
文章目录隐藏
  1. 一、Cargo 基础
  2. 二、Cargo.toml 详解
  3. 三、依赖管理
  4. 四、项目结构与组织
  5. 五、测试
  6. 六、发布 crate
  7. 七、构建优化
  8. 八、常用工具
  9. 九、常见问题
  10. 十、小结

Rust Cargo 完全指南:从 cargo new 到 cargo publish,一篇搞定包管理与构建优化

Cargo 就是 Rust 的包管理器兼构建工具。跟 npm、Maven 差不多。

一、Cargo 基础

1.1 创建项目

# 建二进制项目
cargo new my_project

# 建库项目
cargo new my_library --lib

# 当前目录初始化
cargo init

1.2 项目结构

my_project/
├── Cargo.toml          # 项目配置
├── Cargo.lock          # 依赖锁定文件
└── src/
    ├── main.rs         # 二进制入口
    └── lib.rs          # 库入口

1.3 常用命令

# 构建
cargo build

# 发布模式构建
cargo build --release

# 运行
cargo run

# 测试
cargo test

# 格式化
cargo fmt

# 检查代码(不生成二进制)
cargo check

# 加依赖
cargo add serde

# 加开发依赖
cargo add --dev tokio

# 查看依赖树
cargo tree

# 清理
cargo clean

# 更新依赖
cargo update

# 发布
cargo publish

二、Cargo.toml 详解

2.1 基本结构

[package]
name = "my_project"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <you@example.com>"]
description = "项目描述"
license = "MIT"

[dependencies]
# 依赖

[dev-dependencies]
# 开发依赖(测试用)

[build-dependencies]
# 构建脚本依赖

[[bin]]
name = "my_binary"
path = "src/main.rs"

[lib]
name = "my_library"
path = "src/lib.rs"

[profile.release]
opt-level = 3
lto = true

2.2 版本语义

SemVer:MAJOR.MINOR.PATCH

[dependencies]
# 精确版本
serde = "1.0.100"

# 兼容版本
serde = "1.0"

# 范围
serde = ">=1.0, <2.0"
serde = "^1.0.100"   # >=1.0.100, <2.0.0
serde = "~1.0.100"   # >=1.0.100, <1.1.0

2.3 依赖从哪来

[dependencies]

# crates.io(默认)
serde = "1.0"

# Git 仓库
serde = { git = "https://github.com/serde-rs/serde" }

# 本地路径
my_local_crate = { path = "../my_local_crate" }

# 带特性
serde = { version = "1.0", features = ["derive"] }

# 可选
serde = { version = "1.0", optional = true }

[features]
default = []
with_serde = ["serde"]

三、依赖管理

3.1 加依赖

cargo add serde
cargo add serde --features derive

cargo add --dev tokio
cargo add --build cc

3.2 Cargo.lock

锁定版本,保证每次构建一样。

提交规则:

  • 应用:提交
  • 库:不提交

更新:

cargo update
cargo update -p serde
cargo update -p serde --precise 1.0.100

3.3 看依赖

cargo tree
cargo tree -i serde
cargo tree -d

3.4 冲突怎么办

cargo tree -d
cargo update -p conflicting_crate

四、项目结构与组织

4.1 多二进制项目

[[bin]]
name = "server"
path = "src/bin/server.rs"

[[bin]]
name = "client"
path = "src/bin/client.rs"
project/
├── Cargo.toml
└── src/
    ├── lib.rs
    ├── bin/
    │   ├── server.rs
    │   └── client.rs
    └── utils/
        └── mod.rs

4.2 工作空间

[workspace]
members = [
    "crates/core",
    "crates/cli",
]

[workspace.dependencies]
serde = "1.0"
tokio = "1.0"
# crates/core/Cargo.toml
[package]
name = "my-core"
version = "0.1.0"

[dependencies]
serde = { workspace = true }

4.3 模块组织

// src/lib.rs
pub mod utils;
pub mod models;

pub use utils::helper;
pub use models::User;

// src/utils/helper.rs
pub fn help() {
    println!("Helping...");
}

五、测试

5.1 单元测试

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_add() {
        assert_eq!(add(2, 3), 5);
    }
    
    #[test]
    #[should_panic]
    fn test_panic() {
        panic!("这个会 panic");
    }
    
    #[test]
    fn test_result() -> Result<(), String> {
        if 2 + 2 == 4 { Ok(()) }
        else { Err("算错了".to_string()) }
    }
}

5.2 运行测试

cargo test
cargo test test_add
cargo test -- --ignored
cargo test -- --test-threads=1
cargo test -- --nocapture
cargo test --doc

5.3 集成测试

project/
├── Cargo.toml
├── src/
│   └── lib.rs
└── tests/
    └── integration_test.rs
use my_project::add;

#[test]
fn test_integration() {
    assert_eq!(add(2, 3), 5);
}

5.4 基准测试

推荐用 criterion:

[dev-dependencies]
criterion = "0.5"

[[bench]]
name = "my_benchmark"
harness = false
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn criterion_benchmark(c: &mut Criterion) {
    c.bench_function("add 2+2", |b| b.iter(|| black_box(2 + 2)));
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

六、发布 crate

6.1 准备工作

  1. crates 注册账号
  2. 取 API token
  3. 本地登录:cargo login <token>

6.2 发布前检查

cargo check
cargo test
cargo doc --no-deps
cargo publish --dry-run

6.3 发布

cargo publish

6.4 版本号怎么改

  • PATCH (0.0.x):bug 修复
  • MINOR (0.x.0):新功能
  • MAJOR (x.0.0):破坏性变更

七、构建优化

7.1 编译速度优化

用 sccache:

# .cargo/config.toml
[build]
rustc-wrapper = "sccache"

共享 target 目录:

[build]
target-dir = "/shared/target"

cargo-nextest 跑测试更快:

cargo install cargo-nextest
cargo nextest run

7.2 二进制大小优化

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"
strip = true

看大小:

cargo size --release -- -A

7.3 条件编译

#[cfg(target_os = "linux")]
fn linux_only() {}

#[cfg(feature = "serde")]
fn with_serde() {}

#[cfg(debug_assertions)]
fn debug_only() {}

八、常用工具

8.1 rustfmt

cargo fmt
cargo fmt -- --check

配置 .rustfmt.toml:

edition = "2021"
max_width = 100

8.2 Clippy

cargo clippy
cargo clippy --fix

8.3 rust-analyzer

VS Code 插件,代码补全、跳转、类型提示。

8.4 cargo-audit

cargo install cargo-audit
cargo audit

九、常见问题

Q: Cargo.toml 和 Cargo.lock 区别?

A:

  • Cargo.toml:配置,指定版本范围
  • Cargo.lock:锁定精确版本

Q: cargo check vs cargo build?

A:

  • check:快,不生成二进制
  • build:完整编译

Q: 私有 crate 怎么办?

A:

[dependencies]
my_crate = { version = "1.0", registry = "my-registry" }

十、小结

核心要点

  1. Cargo 是包管理器 + 构建工具;
  2. Cargo.toml 配置,Cargo.lock 锁定版本;
  3. 工作空间管多 crate;
  4. 单元测试 + 集成测试;
  5. 遵循语义化版本发布;
  6. 优化编译速度和大小。

常用命令

命令 用途
cargo build 构建
cargo run 运行
cargo test 测试
cargo check 检查
cargo fmt 格式化
cargo add 加依赖
cargo tree 依赖树
cargo publish 发布

以上关于Rust Cargo完全指南:从cargo new到cargo publish,一篇搞定包管理与构建优化的文章就介绍到这了,更多相关内容请搜索码云笔记以前的文章或继续浏览下面的相关文章,希望大家以后多多支持码云笔记。

「点点赞赏,手留余香」

15

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 admin@mybj123.com 进行投诉反馈,一经查实,立即处理!
重要:如软件存在付费、会员、充值等,均属软件开发者或所属公司行为,与本站无关,网友需自行判断
码云笔记 » Rust Cargo完全指南:从cargo new到cargo publish,一篇搞定包管理与构建优化

发表回复