Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cargo Project

Cargo.toml

Cargo.toml is the manifest file of a Cargo project. It is written in TOML format, and defines metadata, dependencies, and build configuration of the project.

[package]
name = "project_name"
version = "0.0.0"
edition = "2024"

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

# dependencies only used for tests, examples, and benchmarks
[dev-dependencies]
criterion = "0.5"

# dependencies used only in the build script
[build-dependencies]
cc = "1.0"

# named features, can be enabled on the command line
[features]
default = ["std"]
std = []

The crate is named after the name field, and its version is given by version. Command line arguments and environment variables can be read in the build script via std::env; the same applies to features and target configuration.

build.rs

  • Lifecycle: when src/main.rs or src/lib.rs exists, a build script is compiled and run before the package is compiled.
  • Usually used for code generation, (link) configuration, and system control.
// build.rs
fn main() {
    // `cargo:rerun-if-changed` tells cargo to rerun this script when the file changes
    println!("cargo:rerun-if-changed=build.rs");

    // `cargo:rustc-link-lib` links a system library: `-l foo`
    println!("cargo:rustc-link-lib=ssl");
}

OUT_DIR environment variable points to the build output directory, which can be included in the crate via include!.

// build.rs
fn main() {
    let out_dir = std::env::var("OUT_DIR").unwrap(); // directory of the build output
    println!("cargo:rerun-if-changed=src/protos/foo.proto");
    // ... generate code to `{out_dir}/foo.rs`
}

// src/main.rs
include!(concat!(env!("OUT_DIR"), "/foo.rs"));

Workspace

A workspace is a set of packages that share the same Cargo.lock and output directory. The root Cargo.toml defines members; each member is a regular crate. The top-level manifest is not a package itself.

[workspace]
members = [
    "app",
    "crates/foo",
]
# optional resolver config for the shared lockfile
resolver = "3"

[package]   # members are defined in their own manifests
name = "app"
version = "0.0.0"
edition = "2024"

[dependencies]
# workspace deps use `{ package = "foo", path = "crates/foo" }`
foo = { path = "crates/foo" }

Common commands:

cargo new app              # create a new package
cargo add foo              # add a workspace member to `app`
cargo build --workspace    # build all workspace members
cargo run -p app           # run a specific package
cargo test --workspace     # test all workspace members

Each member is versioned and published independently, but they share the lockfile, meaning all resolved versions are consistent across the workspace.