什么是 Rust 项目的推荐目录结构?

31

应该把源代码、示例、文档、单元测试、集成测试、许可证、基准测试等内容放在哪里?

1个回答

55
Cargo是Rust的官方包管理器,定义了一些关于Rust crate布局的约定
.
├── Cargo.lock
├── Cargo.toml
├── benches
│   └── large-input.rs
├── examples
│   └── simple.rs
├── src
│   ├── bin
│   │   └── another_executable.rs
│   ├── lib.rs
│   └── main.rs
└── tests
    └── some-integration-tests.rs
  • Cargo.toml and Cargo.lock are stored in the root of your project.
  • Source code goes in the src directory.
  • The default library file is src/lib.rs.
  • The default executable file is src/main.rs.
  • Other executables can be placed in src/bin/*.rs.
  • Integration tests go in the tests directory (unit tests go in each file they're testing).
  • Example executable files go in the examples directory.
  • Benchmarks go in the benches directory.

These are explained in more detail in the manifest description.

遵循这个标准布局,您将能够使用Cargo的命令轻松构建、运行和测试项目。运行cargo new来设置一个新的可执行项目或者cargo new --lib来设置一个新的库项目。
此外,文档通常是在文档注释中编写的(在任何项之前以///开头的注释,或者用//!来记录父项)。此外,许可证通常放在根目录下。
单元测试与上述相同,在测试函数所在的模块中编写。通常,它们被放置在内部模块中。看起来像这样(这是使用cargo new --lib生成新库时Cargo生成的内容):
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}

1
谢谢!我以为会有更多的内容,但你已经回答了我所有的问题。 - jolson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接