Sub topic 2
One Cargo.lock and One Target Directory
Assume you know basic Rust syntax, cargo build, and the structure of a single-package Cargo.toml. A Cargo workspace groups related packages in one repository.
One lockfile and build directory
A workspace normally has one Cargo.lock and one target directory at its root.
Cargo.lockrecords one compatible version of each external dependency for the workspace.targetstores compiled artifacts shared by all member crates.
This avoids rebuilding the same dependency separately for each crate. It also makes CI builds more predictable because every member uses the same resolved dependency graph.
# Cargo.toml
[workspace]
resolver = "2"
members = ["crates/*"]The root manifest is a virtual manifest because it has a [workspace] table but no [package] table.
Connecting crates with path dependencies
A member can depend on another member with a path dependency. The path identifies the directory containing the dependency's Cargo.toml.
# crates/app/Cargo.toml
[package]
name = "app"
version = "0.1.0"
edition = "2021"
[dependencies]
textkit = { path = "../textkit" }Cargo builds textkit before app. Path dependencies are useful for private libraries and for splitting a large project into focused crates.
Inheriting package metadata
Repeated package metadata can live in the root manifest:
[workspace.package]
version = "0.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"A member opts into inheritance explicitly:
[package]
name = "textkit"
version.workspace = true
edition.workspace = true
license.workspace = trueThe member can still override metadata when a crate needs a different value.
Centralizing dependency versions
Declare shared dependencies once:
[workspace.dependencies]
regex = "1.11"
textkit = { path = "crates/textkit" }A member then enables the shared declaration:
[dependencies]
regex.workspace = true
textkit.workspace = trueThis keeps versions and path definitions consistent. Member-specific settings, such as optional dependencies or enabled features, can be added locally.
Exercise
Why does a workspace usually need only one Cargo.lock file?
Show answer
Cargo resolves the external dependency graph for the workspace together, so one lockfile records compatible versions for all members.