tezvyn:

Rust Cargo Workspaces: A Monorepo Control Panel

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

A Cargo Workspace is a control panel for a multi-crate Rust project, unifying dependencies and build artifacts. Use it for related binaries and libraries to ensure consistent builds.

WHY IT EXISTS As projects grow, managing multiple related Rust crates becomes chaotic. Without a workspace, each crate has its own dependency lock file and its own build output directory. This leads to dependency version conflicts, wasted disk space from redundant build artifacts, and increased overall compile times.

THE MENTAL MODEL Think of a workspace as a "monorepo" manager for Rust. It provides a single root Cargo.toml that acts as a control panel for a collection of member crates. This ensures all crates share one dependency resolution (a single Cargo.lock) and one build cache (a single target directory), making the entire project a single, cohesive unit.

HOW IT WORKS You define a workspace by adding a [workspace] table to a Cargo.toml file in your project's root. This root manifest can be "virtual" (containing only workspace settings) or belong to a "root package" which is also a member. You specify members using the members key, which can include paths and glob patterns like crates/*. All member crates will then use the single Cargo.lock and target directory from the workspace root. Key settings like [patch] and [profile] are only recognized in the root manifest, not in members.

WHEN TO USE IT Use a workspace when your project is composed of multiple, tightly-coupled crates. This is perfect for a web application that has a separate binary for a CLI tool, or a large library that is broken into several smaller implementation crates. The workspace ensures they are always built and tested against the exact same dependency versions.

WHEN NOT TO USE IT Avoid workspaces for completely unrelated projects. If two crates have no logical reason to share dependencies or be developed in lockstep, forcing them into a workspace creates unnecessary coupling. A simple, single-crate project also has no need for a workspace.

ONE CANONICAL EXAMPLE A "virtual" workspace is common for projects without one primary crate. The root Cargo.toml defines the workspace and its members but contains no [package] section itself. For example, a project with a library my_lib and a binary my_cli:

In the project root's Cargo.toml: [workspace] members = ["my_lib", "my_cli"] resolver = "2"

Then, my_lib/Cargo.toml and my_cli/Cargo.toml would each contain their own [package] sections. Running cargo build --workspace from the root builds both, sharing a single target directory and Cargo.lock file.

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.