05-包布局

Cargo 包的标准目录与文件布局

译文 · 基于 The Cargo Book

包布局

原文链接: https://doc.rust-lang.org/cargo/guide/project-layout.html

Cargo 对文件放置有约定,便于你快速上手一个新的 Cargo 包:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
.
├── Cargo.lock
├── Cargo.toml
├── src/
│   ├── lib.rs
│   ├── main.rs
│   └── bin/
│       ├── named-executable.rs
│       ├── another-executable.rs
│       └── multi-file-executable/
│           ├── main.rs
│           └── some_module.rs
├── benches/
│   ├── large-input.rs
│   └── multi-file-bench/
│       ├── main.rs
│       └── bench_module.rs
├── examples/
│   ├── simple.rs
│   └── multi-file-example/
│       ├── main.rs
│       └── ex_module.rs
└── tests/
    ├── some-integration-tests.rs
    └── multi-file-test/
        ├── main.rs
        └── test_module.rs
  • Cargo.toml 与 Cargo.lock 存放在包的根目录(包根)。
  • 源代码放在 src 目录中。
  • 默认库文件是 src/lib.rs。
  • 默认可执行文件是 src/main.rs。
    • 其他可执行文件可放在 src/bin/ 中。
  • 基准测试放在 benches 目录中。
  • 示例放在 examples 目录中。
  • 集成测试放在 tests 目录中。

若二进制、示例、基准测试或集成测试由多个源文件组成,请在 src/bin、examples、benches 或 tests 目录的子目录中放置一个 main.rs,连同额外的模块(module)。可执行文件的名称即为该子目录名。

注意: 按约定,二进制、示例、基准测试与集成测试遵循 kebab-case 命名风格,除非有兼容性理由另做处理(例如与既有二进制名称兼容)。这些目标内的模块采用 snake_case,遵循 Rust 标准。

你可以在《Rust 程序设计语言》中了解更多关于 Rust 模块系统的内容。

关于手动配置目标的更多细节,参见配置目标。关于控制 Cargo 如何自动推断目标名称的更多信息,参见目标自动发现。

最后修改 August 11, 2026: 更新 (70a5af133)