Sub topic 1
Why Workspaces: One Repository, Several Crates
Prerequisites
This chapter assumes you know basic Rust syntax, cargo new, cargo build, and cargo run. You should also know how a single package uses Cargo.toml, and understand the difference between library and binary crates.
Why Workspaces: One Repository, Several Crates
A Cargo workspace groups related Rust packages, also called crates, in one repository. A package can contain a library, a binary, or both. A workspace is useful when an application is split into reusable libraries and executable programs.
The workspace gives all members:
- One
Cargo.lockfile for consistent dependency versions. - One
targetdirectory for shared build artifacts. - Common commands for building, testing, and selecting packages.
- Optional shared metadata, dependencies, and lint settings.
For example, an app binary can use a textkit library while both remain separate packages.
The Root `Cargo.toml` and the `[workspace]` Table
The repository root can contain a virtual manifest with a [workspace] table:
[workspace]
resolver = "2"
members = ["crates/*"]members tells Cargo which packages belong to the workspace. The glob crates/* includes each direct child under crates that contains a package manifest.
The resolver controls how Cargo resolves dependency features. Resolver version 2 is the usual choice for current projects because it avoids some unnecessary feature unification between unrelated dependency uses.
Virtual Manifests and Root Packages
A virtual manifest contains workspace configuration but no [package] table. It is not itself a crate. This is a good default when the root directory exists mainly to organize members.
Alternatively, the root manifest can define a package as well as a workspace:
[package]
name = "project-cli"
version = "0.1.0"
edition = "2021"
[workspace]
members = ["crates/*"]Use a root package when the repository needs a top-level binary or library. Otherwise, a virtual manifest keeps the repository structure explicit.
Choosing Members
You can list members explicitly or use globs:
[workspace]
members = ["crates/*", "tools/release"]
exclude = ["crates/experimental"]
default-members = ["crates/app"]exclude removes matching paths from automatic membership. default-members chooses what Cargo operates on when no package is specified. It does not remove other members. Use it to keep ordinary local commands focused while CI can still build the complete workspace.
Exercise
Does default-members = ["crates/app"] prevent crates/textkit from being built with cargo build --workspace?
Show answer
No. It only changes the default selection when no package-selection flag is given. --workspace still selects every member.