Sub topic 9
Cargo features and conditional compilation
This chapter assumes you can read a Cargo.toml, know the difference between a package and a crate, and have added a dependency before. A feature is a named switch that lets one crate be built in different configurations.
What a feature is
A feature is declared in the [features] table of Cargo.toml. Each feature has a name and a list of things it turns on. Those can be other features or optional dependencies.
[package]
name = "my_geometry"
version = "0.1.0"
edition = "2021"
[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
[dev-dependencies]
pretty_assertions = "1"
[features]
default = []
serde = ["dep:serde"]Two parts matter here:
optional = truemeans Cargo does not buildserdeunless something asks for it.serde = ["dep:serde"]defines a feature namedserdethat turns that dependency on. Thedep:prefix keeps the dependency from also creating an implicit feature of the same name.
The default feature lists features that are on unless the user opts out. Here it is empty, so the crate builds with no extras.
Using a feature in code
Cargo passes each enabled feature to the compiler as a cfg flag. You test it with the #[cfg(...)] attribute. Code that fails the test is removed before type checking, so it never needs its dependencies to exist.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Point {
pub x: i32,
pub y: i32,
}
#[cfg(feature = "serde")]
pub fn serde_enabled() -> bool {
true
}
#[cfg(not(feature = "serde"))]
pub fn serde_enabled() -> bool {
false
}cfg_attr applies an attribute only when the condition holds. Here it adds the derive only with the serde feature on. The two serde_enabled functions are mutually exclusive, so exactly one exists in any build. You can also use the cfg! macro for an ordinary bool expression, but both branches must still compile.
Correction: the diagram must be written as a diagram fence.
Choosing features when building
cargo build
cargo build --features serde
cargo build --no-default-features
cargo test --all-featuresFeatures are additive. If two crates in a dependency graph request different features of the same crate, Cargo builds it once with the union of both. Do not design features that exclude each other, because another crate can turn on both.
Common errors
- Unknown feature name. A misspelled name in
#[cfg(feature = "...")]is silently false. Recent compilers warn through theunexpected_cfgslint, so read those warnings. - Untested combinations. Code behind a feature can rot. Run
cargo testwith default features, with--no-default-features, and with--all-features. - Gated code used elsewhere. If an item is behind
cfg, every use of it needs the same gate. Otherwise the build fails when the feature is off.
Exercise
A crate declares serde = ["dep:serde"] under [features], and a function marked #[cfg(feature = "serde")]. You run cargo build with no flags. Is the function compiled, and is the serde crate built? Which command changes this?
Show answer
Neither. default = [] enables nothing, so the function is removed and the optional serde dependency is not built. Running cargo build --features serde (or --all-features) enables the feature, builds the dependency, and keeps the function.