GGistDev

Cargo

Cargo is Rust’s package manager and build tool. It manages projects, dependencies, builds, tests, and publishing.

Create and run

cargo new hello    # library by default with --lib; binary with --bin
cargo init         # initialize in existing dir
cargo run          # build + run binary
cargo test         # run tests
cargo build --release  # optimized build

Manifest (Cargo.toml)

[package]
name = "myapp"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = { version = "1", features = ["derive"] }
anyhow = "1"

Features

Gate optional functionality and optional dependencies.

[features]
default = []
cli = ["clap"]

[dependencies]
clap = { version = "4", optional = true }

Enable with --features cli or --no-default-features.

Profiles

Tune builds per profile.

[profile.release]
opt-level = 3
lto = true
codegen-units = 1

Workspaces

Share Cargo.lock, target dir, and versions.

# Root Cargo.toml
[workspace]
members = ["core", "cli"]

Each member has its own Cargo.toml and may depend on others via path = "../core".

Build scripts (build.rs)

Run before compilation to generate code or discover system libs. Communicate via cargo:-prefixed lines.

Publishing

  • Add license, repository, readme in Cargo.toml.
  • cargo publish --dry-run then cargo publish.
  • Use exclude/include to control package contents.

Useful commands

cargo check                 # type-check without codegen
cargo fmt && cargo clippy   # format and lint
cargo tree                  # dependency tree