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 - Analyze project to see it has any errors, without building :
cargo check - 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 tokencargo package: make the local create uploadable to crates.iocargo 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.
cargo new crate_name --binORcargo new crate_name: produces an executablecargo new crate_name --lib: 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 buildorcargo run, the executable file will be stored in target/debug/ folder. But when build it viacargo build --releasefor 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
srcdirectory. - 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
testsdirectory (unit tests go in each file they’re testing). - Examples go in the
examplesdirectory. - Benchmarks go in the
benchesdirectory.