Sub topic 10
Organizing multiple crates with workspaces
This chapter assumes you can read a Cargo.toml, know the difference between a package and a crate, and have used path dependencies and cargo test at a basic level. It builds on the earlier chapters about library and binary crates and about dependencies.
Why use a workspace
A single package works until it grows. Soon you want a reusable library, a command-line tool that uses it, and maybe a second tool. You could keep these in three unrelated directories, but each would get its own Cargo.lock and its own target directory. Dependencies would be compiled several times, and two packages could end up with different versions of the same dependency.
A workspace is a set of packages that Cargo builds together. The packages in it are called members. Members share these things:
- One
Cargo.lockat the workspace root, so every member resolves to the same dependency versions. - One
targetdirectory, so a dependency is compiled once and reused by every member. - One set of commands, such as
cargo test --workspace, that act on all members.
Each member is still a normal package with its own Cargo.toml, its own name and version, and its own crates. A workspace does not merge crates. It groups packages.
A minimal workspace
The layout below has a root manifest and two member packages.
my_workspace/
├── Cargo.toml
├── geometry/
│ ├── Cargo.toml
│ └── src/lib.rs
└── cli/
├── Cargo.toml
└── src/main.rsThe root Cargo.toml contains a [workspace] table. It has no [package] table, so it is a virtual manifest: the root directory is not itself a package.
[workspace]
resolver = "2"
members = ["geometry", "cli"]The resolver = "2" line selects the feature resolver. In a virtual manifest Cargo cannot infer it from a package edition, so you should always set it. Newer editions have newer resolver versions, so check the Cargo documentation for the edition you use.
The library member declares its package as usual.
# geometry/Cargo.toml
[package]
name = "geometry"
version = "0.1.0"
edition = "2021"// geometry/src/lib.rs
pub struct Square(pub u32);
impl Square {
pub fn area(&self) -> u32 {
self.0 * self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn area_of_square() {
assert_eq!(Square(4).area(), 16);
}
}The binary member depends on the library through a path dependency.
# cli/Cargo.toml
[package]
name = "cli"
version = "0.1.0"
edition = "2021"
[dependencies]
geometry = { path = "../geometry" }// cli/src/main.rs
use geometry::Square;
fn main() {
let side: u32 = std::env::args()
.nth(1)
.and_then(|s| s.parse().ok())
.unwrap_or(3);
println!("{}", Square(side).area());
}Commands in a workspace
Run these from anywhere inside the workspace. Cargo finds the root by walking up the directory tree.
cargo build --workspace
cargo run -p cli -- 5
cargo test --workspace
cargo test -p geometryWithout a flag, the behavior depends on where you are:
- In a member directory, a command acts on that member only.
- At the root of a virtual manifest,
cargo buildandcargo testact on all members. -p name(or--package name) selects one package by its package name, not by its directory name.--exclude nameremoves a package from a--workspacerun.
To change what a bare command does at the root, set default-members in the [workspace] table. For example, default-members = ["cli"] makes plain cargo run and cargo build at the root use only cli.
What the shared files mean in practice
The shared Cargo.lock is committed to version control for workspaces that contain binaries. It guarantees that everyone builds with the same dependency versions.
The shared target directory lives at the root. Building cli also builds geometry there, and testing geometry later reuses that work. If you delete target, you delete the build artifacts of all members.
Some settings only exist at the root. Profiles such as [profile.release] are read from the root manifest, and the same section in a member manifest is ignored with a warning. If you want link-time optimization or a different opt-level for the whole project, set it at the root.
Sharing metadata and dependency versions
With many members, repeating the same version number in every manifest invites drift. Cargo lets the root define values once, and members inherit them.
# Root Cargo.toml
[workspace]
resolver = "2"
members = ["geometry", "cli"]
[workspace.package]
version = "0.1.0"
edition = "2021"
license = "MIT"
[workspace.dependencies]
geometry = { path = "geometry" }
serde = { version = "1", features = ["derive"] }A member opts in field by field.
# cli/Cargo.toml
[package]
name = "cli"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
geometry = { workspace = true }
serde = { workspace = true }Three rules cover most surprises:
- Inheritance is explicit. A member gets nothing from
[workspace.package]unless it writesfield.workspace = true. [workspace.dependencies]declares a dependency but does not add it to any member. A member must still list it withworkspace = true.- A member can add to an inherited dependency. For example,
serde = { workspace = true, features = ["rc"] }adds thercfeature on top of the shared ones. It can also addoptional = true. It cannot remove features that the root enabled.
Inherited dependencies work for [dev-dependencies] and [build-dependencies] as well. This is a good place to define a test helper crate once for every member.
Dependencies between members
A path dependency such as geometry = { path = "../geometry" } is enough for local development. If you publish a member to crates.io, the registry rejects a dependency that has only a path. Add a version next to it.
geometry = { path = "../geometry", version = "0.1.0" }Cargo uses the path when building locally and the version when the package is published. With [workspace.dependencies] you write this pair once at the root.
Testing across a workspace
Each member keeps its own unit tests, integration tests in its own tests directory, and doc tests. The commands from the previous chapters work per member.
cargo test --workspaceruns everything. It compiles each member's test targets, then runs them one after another, grouped by package.cargo test -p geometry --libruns only the unit tests of that library.cargo test areafilters by test name across every selected package.
An integration test in cli/tests can use geometry as well, because geometry is a normal dependency of cli. Unlike a unit test, it cannot reach private items of either crate.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `current package believes it's in a workspace when it's not` | A package sits under the root directory but is not in `members` | Add it to `members`, or list it in `exclude` |
| Warning that a profile is ignored | A `[profile.*]` section appears in a member manifest | Move it to the root manifest |
| `cargo run` asks which binary to run | Several binary targets exist among the selected packages | Use `cargo run -p cli` |
| Dependency not found despite `[workspace.dependencies]` | The member did not write `workspace = true` | Add the dependency to the member's own table |
| Publishing fails for a path-only dependency | No `version` next to `path` | Add `version`, or define the pair at the root |
When to split into several crates
More crates is not automatically better. A split pays off when:
- Two binaries need the same logic, and a library crate lets them share it.
- You want a clear boundary, because a crate boundary enforces
pubvisibility strictly. - A part of the project changes rarely, and separate crates reduce rebuild times. Cargo recompiles only crates whose inputs changed, and crates can compile in parallel.
- You plan to publish one part on its own.
If none of these applies, modules inside one crate are simpler. Cargo has no cost for modules, but each crate adds a manifest to maintain and a public API to keep stable.
Exercise
A workspace root has members = ["app", "util"]. You run cargo test -p util from the root, and it fails to find the package even though the directory util/ exists. The util/Cargo.toml contains name = "text_util". What is the problem, and what is the correct command?
Show answer
The -p flag selects a package by its package name, which is text_util, not by the directory name util. The correct command is cargo test -p text_util.
Exercise
The root manifest has [workspace.dependencies] with serde = { version = "1", features = ["derive"] }. The member app does not list serde in its own [dependencies], but its code contains use serde::Serialize;. Does it compile? How do you fix it?
Show answer
It does not compile. A [workspace.dependencies] entry only declares a shared definition and adds nothing to any member. Add serde = { workspace = true } to the [dependencies] table in app/Cargo.toml.