tezvyn:

Cargo.toml: Rust's Project Recipe

AI-drafted, machine-checkedSource: doc.rust-lang.orgintermediate

Cargo.toml is your Rust project's recipe, telling the compiler what to build and what dependencies it needs. It defines metadata, production dependencies, and dev-only dependencies for testing.

WHY IT EXISTS To provide a single, declarative source of truth for a Rust project. Without a manifest, you would manually manage compiler flags, dependencies, versions, and build steps, which is error-prone and not scalable. Cargo uses this file to automate that complexity and ensure reproducible builds.

THE MENTAL MODEL Think of Cargo.toml as your project's recipe and instruction manual combined. The [package] section is the cover page, listing the dish's name and version. The [dependencies] sections are the ingredient lists: one for the final dish and another ([dev-dependencies]) for tools used only in the kitchen, like for testing. The [profile] section tells the chef (the compiler) how to cook: quickly for a taste test (dev build) or perfectly for serving (release build).

HOW IT WORKS Cargo.toml is a configuration file written in the TOML format, organized into sections called "tables." The [package] table holds metadata like the crate's name and its SemVer-compliant version. The [dependencies], [dev-dependencies], and [build-dependencies] tables list external crates your project needs. When you run a command like cargo build, Cargo reads this file, resolves the dependency graph, downloads the required crates from a registry like crates.io, and compiles your code with the specified settings.

WHEN TO USE IT You use Cargo.toml for every Rust project managed by Cargo, which is the standard for all but the most trivial single-file scripts. It's where you define your crate's identity, add dependencies like a web framework or serialization library, enable conditional compilation features, and configure different build profiles for development and release.

WHEN NOT TO USE IT For all practical purposes, if you're writing Rust, you're using Cargo and its manifest. The only exception is compiling a single Rust file directly with rustc that has zero external dependencies, which is not a scalable or idiomatic way to build applications.

ONE CANONICAL EXAMPLE A web service needs the tokio runtime and serde for JSON processing. For testing, it uses the mockito library to mock API calls. The Cargo.toml correctly separates these concerns. Under the [dependencies] table, you would list tokio and serde. Under the [dev-dependencies] table, you would list mockito. This ensures mockito is available for cargo test but is not compiled into the final production binary, keeping it lean.

Read the original → doc.rust-lang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.