Cargo,crates and basic project structure
Cargo
Cargo is Rust’s built-in Package Manager. But mainly it uses for,
Create new project :
cargo newUpdate dependencies :
cargo updateBuild project :
cargo buildBuild and run a project :
cargo runRun tests :
cargo testGenerate 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.
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.rsand the second one generates,
├── Cargo.toml
└── src
└── lib.rsCargo.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.rsSource 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.
Last updated