Sub topic 10
Organizing multiple crates with workspaces
This chapter assumes you can create a package with cargo new, know the difference between a library crate and a binary crate, and can declare a dependency in Cargo.toml.
Why use a workspace
A workspace is a set of packages that Cargo builds together. Use one when a project outgrows a single crate. A typical case is a reusable library plus a command-line program that uses it.
Members of a workspace share three things:
- One
Cargo.lock, so every member resolves to the same dependency versions. - One
targetdirectory, so shared dependencies are compiled once. - One set of commands, so
cargo test --workspacechecks everything.
Creating a workspace
Make a directory with a root Cargo.toml that has a [workspace] table and no [package] table. This is called a virtual manifest.
[workspace]
resolver = "2"
members = ["geometry", "cli"]Then create the members inside it:
cargo new geometry --lib
cargo new cliAvoid naming a member core. A crate with that name conflicts with Rust's built-in core crate.
Connecting members
A member depends on a sibling through a path dependency. In cli/Cargo.toml:
[package]
name = "cli"
version = "0.1.0"
edition = "2021"
[dependencies]
geometry = { path = "../geometry" }Now the library can expose an API:
// geometry/src/lib.rs
pub fn area(width: u32, height: u32) -> u32 {
width * height
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn computes_area() {
assert_eq!(area(3, 4), 12);
}
}The binary calls it:
// cli/src/main.rs
fn main() {
println!("{}", geometry::area(3, 4));
}Working across members
Commands run from the root apply to all members. Use -p (package) to pick one.
cargo build
cargo test --workspace
cargo test -p geometry
cargo run -p cliSharing dependency versions
When several members use the same external crate, declare the version once in the root and inherit it in each member:
# root Cargo.toml
[workspace.dependencies]
serde = { version = "1", features = ["derive"] }
# geometry/Cargo.toml
[dependencies]
serde = { workspace = true }This keeps versions from drifting apart between members.
Common errors
- A member is not listed. A package inside the workspace directory that is missing from
membersproduces an error saying the current package believes it is in a workspace when it is not. Add it tomembers. cargo runis ambiguous. If the root is a virtual manifest with several binaries, Cargo cannot choose one. Pass-p cli, or setdefault-membersin the[workspace]table.- Wrong relative path. A
pathdependency is relative to the member's ownCargo.toml, not the root.
Exercise
A workspace has members geometry (library) and cli (binary). You run cargo test -p geometry from the root. Which tests run, and where does Cargo put the compiled output?
Show answer
Only the tests in the geometry package run: its unit tests, integration tests, and doc tests. The cli tests are skipped. Output goes to the single target directory at the workspace root, shared by all members.