Rust Cargo Workspaces
Cargo Workspaces is a feature of Rust’s package manager. Here’s a step-by-step tutorial on how to set up a workspace based on the rust official online doc.
Create a workspace root directory
Create a directory as the root of the a new workspace.
$ mkdir my_workspace
$ cd my_workspace
Initialize Cargo.toml
and [workspace]
section
Inside the workspace, create Cargo.toml
file, add [workspace]
section with member crates that going to be added to this file.
[workspace]
resolver = "2"
members = ["member1", "path/to/member2", "crates/*"]
exclude = ["crates/foo", "path/to/other"]
default-members = ["path/to/member2", "path/to/member3/foo"]
The members
list also supports globs to match multiple paths, using typical filename glob patterns like *
and ?
.
So, for the sake of convenience, we can use crates/*
to set all the sub directory under crates
as member crates for the current workspace.
[workspace]
resolver = "2"
members = ["crates/*"]
Add Member Crates
Under the workspace root directory, use cargo new path [options]
to create member crates. By the way, the path
should be matched with one of members
items in the [workspace]
section of workspace root Cargo.toml
.
cargo new crates/crate1 --lib --vcs none # Creates a new library crate
cargo new crates/crate2 --bin --vcs none # Creates a new binary crate
Package selection
In a workspace, package-related Cargo commands like cargo build
or cargo run can use the -p
/ --package
command-line flags to determine which packages to operate on.
cargo run -p crate2
cargo add dependency -p crate1
The key points
The following key points of workspaces are copied from cargo/reference/workspaces.html
- Common commands can run across all workspace members, like
cargo check --workspace
. - All packages share a common
Cargo.lock
file which resides in the workspace root. - All packages share a common output directory, which defaults to a directory named
target
in the workspace root. - Sharing package metadata, like with
workspace.package
. - The
[patch]
,[replace]
and[profile.*]
sections inCargo.toml
are only recognized in the root manifest, and ignored in member crates’ manifests.