Cargo.toml 结构 ​

核心概念 ​

Cargo.toml 是 Rust 项目的清单文件(manifest),采用 TOML 格式编写,包含了 Cargo 编译项目所需的所有元数据。每个 Rust 包(package)的根目录下都必须有一个 Cargo.toml 文件。它定义了包的名称、版本、依赖关系、编译目标、feature 标志等所有配置信息。

Cargo.toml 由多个段(section)组成,每个段用方括号标记,如 [package]、[dependencies]、[dev-dependencies] 等。cargo new 命令会自动生成一个包含基本配置的 Cargo.toml。

toml
# 一个典型的 Cargo.toml 文件

[package]
name = "my-project"          # 包名(必填)
version = "0.1.0"            # 版本号(必填,语义化版本)
edition = "2024"             # Rust 版本(2015/2018/2021/2024)
authors = ["Alice <alice@example.com>"]  # 作者列表
description = "一个示例项目"   # 简短描述
license = "MIT"              # 开源协议
repository = "https://github.com/alice/my-project"  # 仓库地址
readme = "README.md"         # README 文件路径
rust-version = "1.80"        # 最低 Rust 版本要求

[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1", features = ["full"] }

[dev-dependencies]
criterion = "0.5"

[build-dependencies]
cc = "1.0"

[[bin]]
name = "my-app"
path = "src/main.rs"

[package] 段 ​

toml
[package]
# === 必填字段 ===
name = "my-crate"       # 包名,用于 crates.io 和 use 导入
version = "1.2.3"       # 语义化版本号 major.minor.patch

# === 常用字段 ===
edition = "2024"         # Rust edition,影响语言特性
                         # 可选值:2015, 2018, 2021, 2024
                         # 默认 cargo new 使用最新稳定版

rust-version = "1.80"   # 最低 Rust 工具链版本
                         # 使用低于此版本编译会报错

authors = ["Name <email>"]  # 作者列表
description = "描述文字"     # crates.io 上显示的描述
documentation = "https://docs.rs/my-crate"  # 文档 URL
homepage = "https://example.com"  # 项目主页
repository = "https://github.com/user/repo"  # 源码仓库
license = "MIT OR Apache-2.0"  # SPDX 协议表达式
license-file = "LICENSE"  # 协议文件路径(与 license 二选一)
keywords = ["web", "async"]  # 关键词(最多5个)
categories = ["web-programming"]  # 分类

# === 构建配置 ===
build = "build.rs"       # 构建脚本路径
links = "foo"            # 链接的本地库名称

# === 发布控制 ===
publish = false          # 禁止发布到 crates.io
# publish = ["my-registry"]  # 只允许发布到指定仓库
exclude = ["tests/**", "benches/**"]  # 发布时排除的文件
include = ["src/**", "Cargo.toml"]    # 发布时包含的文件

# === 其他 ===
default-run = "my-app"   # cargo run 默认运行的 binary
autobins = true          # 自动发现 src/bin/ 下的 binary
autoexamples = true      # 自动发现 examples/ 下的示例
autotests = true         # 自动发现 tests/ 下的测试
autobenches = true       # 自动发现 benches/ 下的基准测试
字段必填说明
name是包名,用于依赖引用
version是(发布时)语义化版本号
edition否Rust 版本,默认 2015
rust-version否最低 Rust 版本要求
authors否作者信息
description否(发布时需要)包描述
license否(发布时需要)开源协议
publish否控制发布行为

依赖段 ​

toml
# === [dependencies] 运行时依赖 ===
[dependencies]
# 简写:只指定版本
serde = "1.0"

# 完整写法
serde = { version = "1.0", features = ["derive"] }

# 路径依赖(本地包)
my-lib = { path = "../my-lib" }

# Git 依赖
my-crate = { git = "https://github.com/user/repo", branch = "main" }

# 可选依赖(用于 feature 系统)
openssl = { version = "0.10", optional = true }

# 重命名依赖
rust_serde = { package = "serde", version = "1.0" }

# === [dev-dependencies] 开发依赖 ===
# 仅用于测试、示例、基准测试
[dev-dependencies]
tempfile = "3"
criterion = { version = "0.5", features = ["html_reports"] }
tokio = { version = "1", features = ["test-util", "macros"] }

# === [build-dependencies] 构建脚本依赖 ===
# 仅用于 build.rs
[build-dependencies]
cc = "1.0"
bindgen = "0.69"

目标段(Target) ​

toml
# === [[bin]] 可执行目标 ===
[[bin]]
name = "my-app"         # 可执行文件名
path = "src/main.rs"    # 入口文件路径

[[bin]]
name = "cli-tool"
path = "src/bin/cli.rs"

# === [lib] 库目标 ===
[lib]
name = "my_lib"         # 库名(默认与包名相同,- 替换为 _)
path = "src/lib.rs"     # 库入口
crate-type = ["lib"]    # crate 类型:lib, dylib, staticlib, cdylib, rlib

# === [[example]] 示例 ===
[[example]]
name = "basic"
path = "examples/basic.rs"
required-features = ["full"]  # 需要的 feature

# === [[test]] 集成测试 ===
[[test]]
name = "integration"
path = "tests/integration.rs"

# === [[bench]] 基准测试 ===
[[bench]]
name = "my_bench"
path = "benches/my_bench.rs"
harness = false           # 不使用内置测试框架

Feature 段 ​

toml
[features]
# 默认启用的 feature
default = ["json", "logging"]

# 自定义 feature
json = ["dep:serde", "dep:serde_json"]
logging = ["dep:log", "dep:env_logger"]
full = ["json", "logging", "async"]
async = ["dep:tokio"]

# 依赖中引用
[dependencies]
serde = { version = "1.0", optional = true }
serde_json = { version = "1.0", optional = true }
log = { version = "0.4", optional = true }
env_logger = { version = "0.11", optional = true }
tokio = { version = "1", optional = true, features = ["full"] }

Profile 段 ​

toml
# === 开发构建配置 ===
[profile.dev]
opt-level = 0          # 优化级别(0-3,s,z)
debug = true           # 调试信息
overflow-checks = true # 整数溢出检查

# === 发布构建配置 ===
[profile.release]
opt-level = 3          # 最高优化
debug = false          # 无调试信息
lto = true             # 链接时优化
strip = true           # 剥离符号
panic = "abort"        # panic 时直接终止
codegen-units = 1      # 单代码生成单元(更慢编译,更好优化)

# === 自定义 profile ===
[profile.bench]
opt-level = 3
debug = true           # 基准测试保留调试信息

[profile.test]
opt-level = 0
debug = true

基本示例 ​

toml
# 一个完整的实际项目 Cargo.toml

[package]
name = "web-server"
version = "0.3.1"
edition = "2024"
authors = ["开发团队"]
description = "一个高性能的 Web 服务器"
license = "MIT"
repository = "https://github.com/example/web-server"
rust-version = "1.80"
default-run = "server"

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

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

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

[dependencies]
tokio = { version = "1", features = ["full"] }
axum = "0.7"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres"] }
tracing = "0.1"
tracing-subscriber = "0.3"
anyhow = "1"
tower = "0.4"
tower-http = { version = "0.5", features = ["cors", "trace"] }

[dev-dependencies]
reqwest = { version = "0.12", features = ["json"] }
tokio = { version = "1", features = ["test-util"] }

[build-dependencies]
built = "0.7"

[features]
default = ["postgres"]
postgres = ["sqlx/postgres"]
mysql = ["sqlx/mysql"]
full = ["postgres", "mysql"]

[profile.release]
opt-level = 3
lto = "thin"
strip = "symbols"

[profile.dev.package."*"]
opt-level = 2

常见问题 ​

问题一:name 字段有什么命名规则?

包名只能包含字母、数字、- 和 _,必须以字母开头。在 crates.io 上包名是全局唯一的。代码中引用时 - 会被自动替换为 _(如 my-crate 导入为 use my_crate)。

问题二:edition 字段不写会怎样?

默认使用 2015 版本。cargo new 会自动设置为当前最新稳定版。建议始终显式指定 edition。

问题三:Cargo.toml 和 Cargo.lock 有什么区别?

Cargo.toml 是你手动维护的配置文件,声明依赖的版本范围。Cargo.lock 是 Cargo 自动生成的文件,记录所有依赖的精确版本。库项目通常不提交 Cargo.lock,应用项目应该提交。

问题四:怎么查看 Cargo.toml 中有没有写错的字段?

Cargo 会对未知的字段发出警告。[package.metadata] 段是例外——Cargo 完全忽略它,可以用来存放外部工具的配置。

适用场景 ​

  • 新项目初始化:cargo new 自动生成基本配置
  • 依赖管理:声明运行时、开发、构建依赖
  • 多目标项目:配置库、可执行文件、示例等
  • 发布配置:设置优化级别、LTO、符号剥离
  • 条件编译:通过 features 控制可选功能

注意事项 ​

  • name 和 version 是必填字段
  • 发布到 crates.io 还需要 description 和 license
  • edition 不写默认是 2015,建议始终显式设置
  • [package.metadata] 段被 Cargo 忽略,可存放自定义配置
  • 路径依赖和 git 依赖在发布时必须有对应的 crates.io 版本
  • TOML 格式区分大小写,注意字段名的拼写

总结 ​

Cargo.toml 是 Rust 项目的核心配置文件,采用 TOML 格式。[package] 段定义包的基本信息(名称、版本、edition 等),[dependencies]/[dev-dependencies]/[build-dependencies] 段管理依赖,[[bin]]/[lib] 等段配置编译目标,[features] 段定义可选功能,[profile.*] 段控制编译优化。cargo new 会生成基本模板,开发者根据项目需要逐步完善配置。包名全局唯一(crates.io),edition 建议始终显式设置,发布时需要 description 和 license。