Feature Unification & Additivity
When two crates in one build depend on the same crate with different features, Cargo doesn't build it twice. It builds it once, with the union of all requested features. This is feature unification, and it is the reason for the most important rule in this course: features must be additive. Turning one on may add API and code, never remove or change behaviour that someone else relies on.
Seeing unification happen
A workspace with a library color (default feature names, optional hex) and two binaries: web asks for hex, cli asks for no default features.
mkdir ws && cd ws
printf '[workspace]\nmembers = ["color", "web", "cli"]\nresolver = "3"\n' > Cargo.toml
mkdir -p color/src web/src cli/src
cat > color/Cargo.toml <<'T'
[package]
name = "color"
version = "0.1.0"
edition = "2024"
[features]
default = ["names"]
names = []
hex = []
T
cat > color/src/lib.rs <<'RS'
pub fn describe(r: u8, g: u8, b: u8) -> String {
let mut out = format!("rgb({r}, {g}, {b})");
if cfg!(feature = "names") && (r, g, b) == (255, 0, 0) { out.push_str(" red"); }
if cfg!(feature = "hex") { out.push_str(&format!(" #{r:02x}{g:02x}{b:02x}")); }
out
}
RS
printf '[package]\nname = "web"\nversion = "0.1.0"\nedition = "2024"\n\n[dependencies]\ncolor = { path = "../color", features = ["hex"] }\n' > web/Cargo.toml
printf '[package]\nname = "cli"\nversion = "0.1.0"\nedition = "2024"\n\n[dependencies]\ncolor = { path = "../color", default-features = false }\n' > cli/Cargo.toml
for p in web cli; do echo 'fn main() { println!("{}", color::describe(255, 0, 0)); }' > $p/src/main.rs; done
echo "--- build each package on its own"
cargo run -q -p cli
cargo run -q -p web
echo "--- build the whole workspace, then run cli"
cargo build -q --workspace
./target/debug/cli
echo "--- why?"
cargo tree -e features -i color --workspace--- build each package on its own
rgb(255, 0, 0)
rgb(255, 0, 0) red #ff0000
--- build the whole workspace, then run cli
rgb(255, 0, 0) red #ff0000
--- why?
color v0.1.0 (/home/learner/ws/color)
└── cli v0.1.0 (/home/learner/ws/cli)
└── cli feature "default" (command-line)
├── color feature "default" (command-line)
│ └── web v0.1.0 (/home/learner/ws/web)
│ └── web feature "default" (command-line)
├── color feature "hex"
│ └── web v0.1.0 (/home/learner/ws/web) (*)
└── color feature "names"
└── color feature "default" (command-line) (*)
Built on its own, cli gets a bare color. Built together with web, the same cli source produces a binary with names and hex behaviour it never asked for, because there is only one color in that build and it has every feature anyone requested. cargo tree -e features -i color shows who enabled what.
With additive features that's harmless: cli just got some code it doesn't call. The danger starts when a feature changes behaviour, or when two features exclude each other.
When features aren't additive
A common anti-pattern: a storage crate with features mem and disk that pick a backend, guarded by compile_error! because both can't work at once:
mkdir ws && cd ws
printf '[workspace]\nmembers = ["store", "server", "tool"]\nresolver = "3"\n' > Cargo.toml
mkdir -p store/src server/src tool/src
printf '[package]\nname = "store"\nversion = "0.1.0"\nedition = "2024"\n\n[features]\nmem = []\ndisk = []\n' > store/Cargo.toml
cat > store/src/lib.rs <<'RS'
#[cfg(all(feature = "mem", feature = "disk"))]
compile_error!("features `mem` and `disk` are mutually exclusive");
#[cfg(feature = "disk")]
pub const BACKEND: &str = "disk";
#[cfg(not(feature = "disk"))]
pub const BACKEND: &str = "mem";
RS
printf '[package]\nname = "server"\nversion = "0.1.0"\nedition = "2024"\n\n[dependencies]\nstore = { path = "../store", features = ["disk"] }\n' > server/Cargo.toml
printf '[package]\nname = "tool"\nversion = "0.1.0"\nedition = "2024"\n\n[dependencies]\nstore = { path = "../store", features = ["mem"] }\n' > tool/Cargo.toml
for p in server tool; do echo 'fn main() { println!("{}: {}", env!("CARGO_PKG_NAME"), store::BACKEND); }' > $p/src/main.rs; done
cargo run -q -p server
cargo run -q -p tool
echo "--- now build both at once (cargo build, cargo test --workspace, CI...)"
cargo build --workspace 2>&1server: disk
tool: mem
--- now build both at once (cargo build, cargo test --workspace, CI...)
Compiling store v0.1.0 (/home/learner/ws/store)
error: features `mem` and `disk` are mutually exclusive
--> store/src/lib.rs:2:1
|
2 | compile_error!("features `mem` and `disk` are mutually exclusive");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error: could not compile `store` (lib) due to 1 previous error
Each package builds alone. The workspace build fails, and so would any downstream project that happens to depend on both a mem user and a disk user, even if those are third-party crates its author never looked inside. Mutually exclusive features push a conflict onto people who can't fix it.
Better designs:
- Make both available: compile both backends when both features are on, and pick one at runtime (
Store::memory(),Store::disk(path)). - Use a type or a generic parameter instead of a feature to choose the implementation.
- If a choice truly must be global (an allocator, a TLS library), make it the final binary's decision, ideally through a non-feature mechanism, and document it loudly.
What the resolver does not unify
Unification is across one build, not across everything. The feature resolver (version "2", the default since edition 2021; "3" from edition 2024 adds MSRV-aware version selection on top) keeps features apart in three cases:
| Not unified | Example |
|---|---|
| build-dependencies and proc-macros vs normal dependencies | build.rs uses serde with std; your no_std firmware still gets serde without std |
| dev-dependencies, unless you're building a target that needs them | a test-only feature doesn't leak into cargo build |
| platform-specific dependencies for other targets | a cfg(windows) dependency's features don't affect a Linux build |
The old resolver "1" unified all of these, which is why edition-2018 workspaces sometimes saw std turned on in an embedded build by a build script. A workspace's resolver is set only in the root manifest ([workspace] resolver = "3"), because workspaces have no edition of their own.
A model of unification
The rule is simple to state as code: walk the graph from the packages being built, and for each crate collect every feature any edge requests, expanding features that enable other features. Building cli alone and building the whole workspace give different answers:
FEATURES = {"color": {"default": ["names"], "names": [], "hex": []}}
DEPS = { # package -> [(dependency, requested features, default-features?)]
"web": [("color", ["hex"], True)],
"cli": [("color", [], False)],
"color": [],
}
def expand(crate, feats):
out, todo = set(), list(feats)
while todo:
f = todo.pop()
if f not in out:
out.add(f)
todo += FEATURES.get(crate, {}).get(f, [])
return out
def resolve(roots):
enabled, todo, seen = {}, list(roots), set()
while todo:
pkg = todo.pop()
if pkg in seen:
continue
seen.add(pkg)
for dep, feats, defaults in DEPS[pkg]:
want = list(feats) + (["default"] if defaults else [])
enabled[dep] = enabled.get(dep, set()) | expand(dep, want) # the union
todo.append(dep)
return {k: sorted(v) for k, v in enabled.items()}
print("cargo build -p cli ->", resolve(["cli"]))
print("cargo build -p web ->", resolve(["web"]))
print("cargo build --workspace ->", resolve(["web", "cli"]))cargo build -p cli -> {'color': []}
cargo build -p web -> {'color': ['default', 'hex', 'names']}
cargo build --workspace -> {'color': ['default', 'hex', 'names']}
Real Cargo also tracks which edges are build, dev or platform-specific (the table above), but the core is a set union, which is exactly why features have to be additive.
Test yourself
web needs color with hex, cli needs color with no default features. What does cli get in cargo build --workspace?
- Exactly what it asked for
- The union: default features and hex
- A second copy of color without features
- A build error
Why are mutually exclusive features (mem vs disk with compile_error!) a bad design?
- compile_error! is unstable
- Any build that contains users of both fails, including downstream projects that can't change either
- Features can't contain constants
- They slow down the resolver
Under resolver 2/3, does a feature enabled on serde by a build-dependency turn on that feature for the normal serde dependency?
- Yes, always
- No: build-dependencies and proc-macros are resolved separately from normal dependencies
- Only in release builds
- Only with --all-features