Rust 项目推荐的目录结构是什么? [英] What is the recommended directory structure for a Rust project?
问题描述
应该将源代码、示例、文档、单元测试、集成测试、许可证、基准测试等放在哪里?
Cargo,Rust 的官方包管理器,定义了一些关于 Rust crate 布局的约定:
<块引用>.├── 货物锁├── Cargo.toml├── 长凳│ └── 大输入.rs├── 例子│ └── simple.rs├── src│ ├── bin│ │ └── another_executable.rs│ ├── lib.rs│ └── main.rs└── 测试└── some-integration-tests.rs
Cargo.toml
和Cargo.lock
存储在项目的根目录中.- 源代码位于
src
目录中. - 默认库文件是
src/lib.rs
. - 默认的可执行文件是
src/main.rs
. - 其他可执行文件可以放在
src/bin/*.rs
中. - 集成测试位于
tests
目录中(单元测试位于他们正在测试的每个文件中). - 示例可执行文件位于
examples
目录中. - 基准位于
benches
目录中.
这些在 中有更详细的解释清单说明.
通过遵循此标准布局,您将能够使用 Cargo 的命令轻松构建、运行和测试您的项目.运行 cargo new
来设置一个新的可执行项目,或者运行 cargo new --lib
来设置一个新的库项目.
此外,库的文档通常写在文档注释中(注释在任何项之前以 ///
开头,或以 //!
开头以记录父项).此外,许可证通常放在根目录下.
如上所述,单元测试与它们正在测试的函数在同一个模块中编写.通常,它们被放在一个内部模块中.它看起来像这样(这是 Cargo 为带有 cargo new --lib
的新库生成的):
#[cfg(test)]模组测试{#[测试]fn it_works() {}}
Where should one put the sources, examples, documentation, unit tests, integration tests, license, benchmarks etc?
Cargo, the official package manager for Rust, defines some conventions regarding the layout of a 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
andCargo.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.
By following this standard layout, you'll be able to use Cargo's commands to build, run and test your project easily. Run cargo new
to set up a new executable project or cargo new --lib
to set up a new library project.
Additionally, documentation for libraries is often written in documentation comments (comments that start with ///
before any item, or //!
to document the parent item). Also, the license is usually put at the root.
Unit tests, as mentioned above, are written in the same module as the functions they're testing. Usually, they're put in an inner module. It looks like this (this is what Cargo generates for a new library with cargo new --lib
):
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
}
}
这篇关于Rust 项目推荐的目录结构是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!