Where should one put the sources, examples, documentation, unit tests, integration tests, license, benchmarks etc?
Rust projects are organized into crates which form a single distribution unit, like a static object or a DLL. Source within a crate is organized into modules, which are like namespaces but provide an additional privacy boundary. Not everything in a module has to be publicly exported to other modules.
The . cargo/bin directory of your home directory is the default location of Rust binaries. Not only the official binaries like rustup , rustc , cargo , rustfmt , rustdoc , rls and also the binaries you can install via cargo install command, will be stored in this directory.
Rust provides a powerful module system that can be used to hierarchically split code in logical units (modules), and manage visibility (public/private) between them. A module is a collection of items: functions, structs, traits, impl blocks, and even other modules.
An extern crate declaration specifies a dependency on an external crate. The external crate is then bound into the declaring scope as the identifier provided in the extern crate declaration.
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() { } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With