Cargo,crates and basic project structure

Cargo

Cargo is Rust’s built-in Package Manager. But mainly it uses for,

  • Create new project : cargo new

  • Update dependencies : cargo update

  • Build project : cargo build

  • Build and run a project : cargo run

  • Run tests : cargo test

  • Generate documentation via rustdoc : cargo doc

Other than that there are some cargo commands, especially for publishing crates directly via cargo.

  • cargo login : acquiring an API token

  • cargo package : make the local create uploadable to crates.io

  • cargo publish : make the local create uploadable to crates.io and upload the crate

Crate

⭐️ A crate is a package. Crates can be shared via Cargo.

A crate can produce an executable or a library. In other words, it can be a binary crate or a library crate. 01. cargo new crate_name --bin : produces an executable 02. cargo new crate_name --lib OR cargo new crate_name: produces a library

The first one generates,

├── Cargo.toml
└── src
    └── main.rs

and the second one generates,

├── Cargo.toml
└── src
    └── lib.rs
  • Cargo.toml(capital c) is the configuration file which contains all of the metadata that Cargo needs to compile your project.

  • src folder is the place to store the source code.

  • Each crate has an implicit crate root/ entry point. main.rs is the crate root for a binary crate and lib.rs is the crate root for a library crate.

💡 When we build a binary crate via cargo build or cargo run, the executable file will be stored in target/debug/ folder. But when build it via cargo build --release for a release it will be stored in target/release/ folder.

Project Structure

This is how Cargo Docs describes about the recommended Project Layout,

.
├── 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
  • 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).

  • Examples go in the examples directory.

  • Benchmarks go in the benches directory.

Last updated