Sub topic 1
Why workspaces: one repository, several crates
A Cargo workspace is a set of packages that live in one repository and are built together. The packages share one Cargo.lock, one target directory, and, if you choose, common metadata and dependency versions. This chapter explains the problem workspaces solve, what you get from one, and where the model has limits. Later chapters cover each setting in detail.
Prerequisites
This chapter assumes you can do the following:
- Write basic Rust and use
cargo new,cargo buildandcargo run. - Read a
Cargo.tomlfor a single package, including the[package]and[dependencies]tables. - Tell a library crate (
src/lib.rs) from a binary crate (src/main.rs). - Declare dependencies and features in
Cargo.toml.
You do not need any workspace experience.
The problem: several crates that belong together
Most Rust projects start as one package. As the code grows, a single crate becomes awkward in a few common ways:
- Compile times grow. The compilation unit in Rust is the crate. Changing one line recompiles the whole crate, so large crates rebuild slowly.
- Boundaries blur. Everything in one crate can reach everything else through
pub(crate). Splitting into crates makes the public API of each part explicit. - Reuse gets harder. You may want a command-line tool and a web service to share the same parsing code. That code belongs in a library that both binaries depend on.
- Dependencies leak. A command-line binary needs
clap. A core library should not.
The obvious fix is to split the project into several packages. Without workspaces, each package would be its own project with its own Cargo.lock and target directory. You would have to keep dependency versions in sync by hand, and you would build the same dependencies several times. A workspace removes that overhead.
What a workspace gives you
A workspace has a root Cargo.toml with a [workspace] table. Every member package is built in the context of that root. This gives you four things.
| Benefit | What it means in practice |
|---|---|
| One `Cargo.lock` | All members resolve to the same versions of each dependency. |
| One `target` directory | A dependency used by three members is compiled once and reused. |
| Shared settings | Version, edition, license, dependency versions and lints can be declared once. |
| Whole-project commands | `cargo build --workspace` and `cargo test --workspace` act on every member. |
Each member is still a normal package with its own Cargo.toml, its own name and its own dependencies. A workspace does not merge packages into one crate. It coordinates them.
A minimal example
The example below uses the layout this tutorial builds on. It has a library called textkit and a binary called app that uses it.
my-project/
├── Cargo.toml
├── Cargo.lock
├── target/
└── crates/
├── textkit/
│ ├── Cargo.toml
│ └── src/lib.rs
└── app/
├── Cargo.toml
└── src/main.rsThe root Cargo.toml has a [workspace] table and no [package] table. This is called a virtual manifest.
[workspace]
resolver = "2"
members = ["crates/*"]
[workspace.package]
version = "0.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
[workspace.dependencies]
textkit = { path = "crates/textkit" }
[workspace.lints.rust]
unsafe_code = "forbid"The members line uses a glob, so any directory under crates/ that contains a Cargo.toml becomes a member. The [workspace.package], [workspace.dependencies] and [workspace.lints] tables hold values that members can inherit.
The library inherits its metadata and lints:
[package]
name = "textkit"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = trueThe binary does the same, and it also depends on textkit through the workspace entry:
[package]
name = "app"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
textkit.workspace = true
[lints]
workspace = trueThe library code in crates/textkit/src/lib.rs:
pub fn shout(input: &str) -> String {
format!("{}!", input.to_uppercase())
}The binary in crates/app/src/main.rs:
fn main() {
println!("{}", textkit::shout("hello"));
}Run these commands from anywhere inside the workspace:
cargo build --workspace
cargo test -p textkit
cargo run -p app
cargo build --workspace --exclude appcargo run -p app prints HELLO!. You get the same result whether your shell is in the root or in crates/app, because Cargo searches upward from the current directory for a manifest that lists the current package as a member.
How Cargo finds the workspace
When you run a command, Cargo does not look only at the current directory. It starts at the nearest Cargo.toml and then walks up the directory tree looking for a manifest with a [workspace] table. If it finds one that includes the current package as a member, that root controls the build.
This explains several behaviors:
- The
Cargo.lockandtargetdirectory always sit next to the root manifest, not next to the member you are in. - A command run inside
crates/textkitwith no flags acts ontextkitonly. At the root of a virtual manifest, with no flags, it acts on all members (or ondefault-membersif you set it). - A package in a subdirectory of the workspace root that is not listed in
membersproduces an error when Cargo finds the enclosing workspace. You must add it tomembersor toexclude.
The second diagram shows the same discovery process as a flow.
The shared lock file and target directory
Two files and directories are shared across the workspace, and both have consequences worth knowing early.
One Cargo.lock. The lock file records the exact version of every dependency in the whole workspace. If textkit and app both use serde, they use the same version. This avoids a class of bugs where two members work in isolation but fail together. The cost is that you cannot give two members different versions of a crate through a normal version requirement, because Cargo picks one compatible version for the shared requirement. Different semver-incompatible versions (for example serde 0.9 and serde 1.0) can both exist, but each requirement still resolves to one version across the workspace.
One target directory. Build output goes to <root>/target. If three members depend on regex, Cargo compiles regex once. On a large project this saves substantial time and disk space. It also means that cargo clean at any point in the workspace removes the build output for all members. Use cargo clean -p textkit to remove only one package's artifacts.
Workspaces and path dependencies
Members refer to each other with path dependencies. In the example, the root declares textkit = { path = "crates/textkit" } once, and app writes textkit.workspace = true. The path is resolved relative to the workspace root, not relative to app.
If you do not use [workspace.dependencies], you can write the path directly in each member:
[dependencies]
textkit = { path = "../textkit" }Both forms are valid. Path dependencies between members are not special-cased by Cargo, though. Any package can use a path dependency, and being in the same workspace is not required. Membership only determines whether the packages share a lock file, a target directory and inheritable settings.
When a workspace is the right choice
A workspace fits when the packages are developed together and released as a group, or at least tested together. Typical cases:
- A library with a command-line frontend.
- A core library with optional adapters, such as one crate per database backend.
- A procedural macro crate and the library that uses it. Cargo requires proc macros to live in their own crate, so a workspace is the natural home.
- A large application split into layers to improve incremental compile times.
A workspace is a weaker fit in these cases:
- The packages have independent release cycles and different maintainers. Separate repositories may be simpler.
- You need different dependency versions or different toolchains for different parts. A single lock file and shared settings get in the way.
- The project is small enough that one crate with modules is clear. Extra crates add manifest files and publishing work with little gain.
A workspace is also not the same as a package with several targets. One package can contain a library, several binaries (src/bin/*.rs), examples and tests. Choose a workspace when you need separate packages with their own dependency lists and names. Choose multiple targets in one package when the pieces share one dependency list and one version.
Common mistakes
- Expecting
cargo buildat a virtual root to build one crate. With no[package]table, Cargo builds all members, or thedefault-membersif set. Use-p nameto select one. - Adding a crate directory without registering it. If the new directory is under the workspace root but not matched by
members, Cargo reports that the package believes it is in a workspace when it is not. Add it tomembersorexclude. - Putting
Cargo.lockin.gitignorefor a binary workspace. Commit the lock file when the workspace produces applications, so builds are reproducible. - Defining profiles in a member manifest. Profiles such as
[profile.release]are read from the workspace root only. Cargo ignores them in members and prints a warning.
What the rest of the tutorial covers
This chapter introduced the idea. The next chapters go through the root manifest, virtual manifests versus root packages, the members, exclude and default-members keys, and the lock file and target directory in detail. After that come inheritance of package metadata, dependencies and lints, selection flags, resolver versions and feature unification, root-only settings, publishing, and CI layout.
Exercise
You have a workspace with members core, cli and server. All three use tokio. How many times is tokio compiled in a clean build with the same profile and features, and how many Cargo.lock files exist? Why?
Show answer
tokio is compiled once for a given set of features and profile, because all members share the single target directory at the workspace root. (If the members enable different features, Cargo unifies them with the default resolver behavior for normal builds, so one build with the combined features is usually enough.) There is one Cargo.lock, located next to the root manifest, and it records one resolved tokio version for every member.
Exercise
You run cargo build at the root of a virtual manifest that has three members, and no default-members key. Which packages are built? How do you build only cli?
Show answer
All three members are built, because a virtual manifest has no root package and the default is every member. To build only cli, run cargo build -p cli, or run cargo build from inside the cli directory.
Exercise
A teammate adds crates/extras/Cargo.toml to a workspace whose root lists members = ["crates/textkit", "crates/app"]. Cargo now reports an error about a workspace. What are two ways to fix it?
Show answer
Add "crates/extras" to members so it becomes part of the workspace. Or add "crates/extras" to the exclude list in [workspace] so Cargo treats it as standalone, outside the workspace.