Skip to content
rusthacks.dev

Cargo Toml Explained Section by Section With Real Examples

Every section of Cargo.toml that matters, with an example: package metadata, dependency forms, dev and build dependencies, features, targets, profiles and lints.

6 min read
Summarize in AI
Flat illustration for the post “Cargo Toml Explained Section by Section With Real Examples”, composed around cargo.

A Cargo.toml file looks like a list of settings until the day a build behaves strangely and you discover that half of the lines mean something other than what you assumed. version = "1.2" is not "exactly 1.2". edition is not the compiler version. A dev dependency is invisible to the people who depend on you. This post walks the manifest table by table, builds a real crate with it, and shows what Cargo says when you get a table wrong.

Everything below ran on Cargo 1.99 with edition 2024, with serde as the one external crate.

Start with a manifest that builds

The smallest useful manifest has a [package] table and a source file. Create a crate and replace the generated manifest with a fuller one that uses most of the tables you will meet:

Cargo.tomlTOML
[package]
name = "weather-cli"
version = "0.3.1"
edition = "2024"
rust-version = "1.85"
description = "Print the forecast in your terminal"
license = "MIT OR Apache-2.0"
repository = "https://github.com/example/weather-cli"
readme = "README.md"
keywords = ["weather", "cli"]
categories = ["command-line-utilities"]

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

[dev-dependencies]
pretty_assertions = "1"

[features]
default = ["metric"]
metric = []
imperial = []

[lints.clippy]
pedantic = { level = "warn", priority = -1 }

[profile.release]
lto = "thin"
strip = true

Pair it with a program that uses a dependency and a feature, so the manifest is exercised rather than just parsed:

src/main.rsrust
use serde::Serialize;

#[derive(Serialize)]
struct Reading {
    city: &'static str,
    temp: f64,
    unit: &'static str,
}

fn main() {
    let unit = if cfg!(feature = "imperial") { "F" } else { "C" };
    let temp = if unit == "F" { 68.0 } else { 20.0 };
    let r = Reading { city: "Oslo", temp, unit };
    println!("{} {:.1}{}", r.city, r.temp, r.unit);
}
Text
$ cargo run -q
Oslo 20.0C
$ cargo run -q --no-default-features --features imperial
Oslo 68.0F

The second run proves the point of the [features] table: the same source produces two programs, chosen at the command line, with no edit to the code. The rest of this post explains what each table did to make that happen.

package: identity, compiler floor and publishing metadata

name and version identify the crate; together they are the key in the registry and in Cargo.lock. edition selects a set of language rules for this crate only. It is not the compiler version: a crate on edition 2021 and a crate on edition 2024 link together fine, which is why you can adopt a new edition one crate at a time. See editions explained for what each one changes.

rust-version is the minimum supported Rust version. Cargo refuses to build on an older compiler and prints the version it found. Since Cargo 1.84 the resolver can also prefer dependency versions whose own rust-version fits yours, which is the practical reason to declare it. The longer treatment is in declaring your MSRV.

The remaining fields exist for cargo publish. description and license (an SPDX expression, or license-file) are mandatory; repository, readme, keywords (at most five) and categories make the crate findable. Binary crates that never publish can leave them out and set publish = false so a stray cargo publish fails loudly instead of leaking source.

Dependency tables and what the version string means

A bare version string is a caret requirement. Cargo reads it as "any version that is semver compatible with this", and the meaning shifts when the major version is zero, because in 0.x the minor number is the breaking one:

WrittenMeansWhy
serde = "1">=1.0.0, <2.0.0major 1 promises compatibility
serde = "1.0.200">=1.0.200, <2.0.0still caret, floor raised
rand = "0.8.5">=0.8.5, <0.9.0in 0.x the minor is breaking
x = "=1.2.3"exactly 1.2.3an exact pin, used rarely
x = "~1.2">=1.2.0, <1.3.0tilde allows patch updates only

A dependency can come from three places, and you can combine a path with a version so the local checkout is used in development and the registry version is used once you publish:

Cargo.tomlTOML
[dependencies]
from_registry = "1"
from_git = { git = "https://github.com/example/tool", rev = "a1b2c3d" }
from_path = { path = "../shared", version = "0.2" }
renamed = { package = "real-crate-name", version = "3" }

package = "..." renames a dependency locally, which is how one crate depends on two majors of the same library at once. default-features = false drops a crate's default features, and it is the single most effective way to shrink a dependency tree; the full mechanics are in feature unification.

Dev, build and target-specific dependencies

[dev-dependencies] compile for tests, examples and benchmarks and are never pulled in by people who depend on your library. [build-dependencies] compile for build.rs and are built for the host machine, which matters when you cross-compile. A dependency that only makes sense on one platform goes under a cfg key:

Cargo.tomlTOML
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.59", features = ["Win32_Foundation"] }

[target.'cfg(unix)'.dependencies]
libc = "0.2"

A common mistake is putting a test helper in [dependencies]. Your library then ships it to every user, and it shows up in cargo tree for people who never run your tests.

Features declare optional behaviour

A feature is a name that maps to a list of things it turns on: other features or optional dependencies. The dep: prefix enables an optional dependency without also creating an implicit feature of the same name, which keeps your public feature list honest:

Cargo.tomlTOML
[dependencies]
serde_json = { version = "1", optional = true }

[features]
default = []
json = ["dep:serde_json"]

Features must be additive. Turning one on may add code but should never remove or change the meaning of existing items, because Cargo takes the union of every crate's requested features across the whole graph. Optional dependencies covers the patterns that survive that rule.

When Cargo rejects the manifest

Three failures account for most manifest errors. Forget the version on a dependency and you get this:

TOML
[dependencies]
serde = { features = ["derive"] }
Text
error: failed to parse manifest at `/work/weather-cli/Cargo.toml`

Caused by:
  dependency (serde) specified without providing a local path, Git repository, version, or workspace dependency to use

Delete src/main.rs and src/lib.rs and Cargo reports that the package has nothing to build:

Text
error: failed to parse manifest at `/work/weather-cli/Cargo.toml`

Caused by:
  no targets specified in the manifest
  either src/lib.rs, src/main.rs, a [lib] section, or [[bin]] section must be present

And publishing without a license stops at the packaging step, before anything leaves your machine:

Text
error: failed to verify manifest at `/work/weather-cli/Cargo.toml`

Caused by:
  missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for more information on configuring these fields

Each message names the field, which is the useful part. Read the "Caused by" lines rather than the first line.

Targets, profiles and lints

Cargo finds src/main.rs, src/lib.rs, src/bin/*.rs, tests/, examples/ and benches/ by convention, so you rarely write a [[bin]] or [lib] table. Add one only to change a name or path, for example to give the binary a different name from the package. [profile.dev] and [profile.release] tune the compiler; see profiles explained. [lints] sets lint levels in one place instead of a #![warn(...)] attribute at the top of every crate.

Inspect what Cargo understood

When behaviour surprises you, ask Cargo instead of reading the file harder. cargo metadata --format-version 1 prints the fully resolved manifest as JSON, cargo tree -e features shows which features each crate received, and cargo package --list prints exactly which files would be published. Run the last one before every first publish: it is how people discover that their .env or a 40 MB fixture directory was about to go to the registry.

Where this overview stops

This is the single-package view. A workspace adds a root [workspace] table and lets members inherit fields with workspace = true; that changes where several of these tables live and is covered in workspaces explained. The manifest also supports [patch], [replace], [badges] and unstable keys that need a nightly Cargo; each has its own post, and none is needed to build a working crate. The authoritative field list is the manifest reference.

Also inRust
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.