Sub topic 3
Reading and Editing Cargo.toml
Assume you can use a terminal and understand that Cargo is Rust’s package manager and build tool. This chapter focuses on an existing Cargo project.
Cargo.toml and Dependencies
Cargo.toml is the project manifest. It records package metadata and the crates, or Rust packages, that your project needs.
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]| Section | Purpose |
|---|---|
| `[package]` | Names the package and selects its Rust edition. |
| `[dependencies]` | Lists crates required by the program. |
Add a crate from crates.io with Cargo:
cargo add randCargo updates [dependencies] with a compatible rand version. It also records the exact resolved versions in Cargo.lock. Commit Cargo.lock for applications so builds remain repeatable. Libraries often leave lockfile policy to their users.
Build Profiles
Cargo has profiles for different goals:
cargo check
cargo build
cargo build --releasecargo check type-checks quickly without producing a final executable. cargo build creates an unoptimized debug build in target/debug. cargo build --release enables optimizations and writes to target/release. Release builds run faster but take longer to compile.
Toolchains and Release Channels
rustup installs and manages Rust toolchains. Update the default toolchain with:
rustup update
rustup default stable
rustup toolchain listRust has release channels such as stable, beta, and nightly. Use stable for most projects. A project can select a channel with a rust-toolchain.toml file, but nightly features may change or break.
Libraries, Tests, and Checks
Create a library crate with cargo new --lib calculator. Its main source file is src/lib.rs:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_numbers() {
assert_eq!(add(2, 3), 5);
}
}Run its tests and standard checks:
cargo test
cargo fmt
cargo clippycargo fmt formats Rust code. cargo clippy reports common mistakes and improvement suggestions.
Exercise
Which command creates an optimized executable?
Show answer
cargo build --release.