Cargo is Rust’s built-in package manager and the build system. It can be used to,
- Create a new project:
- Build the project:
- Run the project:
- Update project dependencies:
- Run tests:
- Generate the project documentation via rustdoc:
- Analyze the project to see it has any errors, without building it:
In addition, there are
cargo commands to publish the project as a crate/ package to Rust’s official crate registry, crates.io.
💡 We need to get an API token from crates.io to publish a crate to it. The API token can be found in the Account Settings page, after login to that site. We will discuss more about this under code organization with crates.
- Log in to crates.io with the API token:
- Make the local crate uploadable to crates.io:
- Upload the crate to crates.io:
A crate is a package, which can be shared via crates.io. 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 --binor
cargo new crate_name: Produces an executable
cargo 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 run, the executable file will be stored in target/debug/ folder. But when building it via
cargo build --releasefor a release it will be stored in target/release/ folder.
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
- The source code goes in the
- The default library file is
- The default executable file is
- Other executables can be placed in
- Integration tests go in the
testsdirectory (unit tests go in each file they’re testing).
- Examples go in the
- Benchmarks go in the