Answer#
A Cargo feature is a name you define in Cargo.toml. Code and dependencies can depend on that name, and whoever builds the crate decides whether it is on. Nothing is compiled for a feature that is off, so an optional dependency costs nothing when its feature is not enabled.
How to do it#
- Mark the dependency
optional = trueand give it a feature. Thedep:prefix keeps the dependency's own name from becoming a second, implicit feature.
[package]
name = "feat"
version = "0.1.0"
edition = "2024"
[dependencies]
serde_json = { version = "1", optional = true }
[features]
default = []
json = ["dep:serde_json"]- Guard the code that needs it with
#[cfg(feature = "...")], or ask withcfg!(feature = "...").
fn describe(items: &[(&str, u32)]) -> String {
#[cfg(feature = "json")]
{
serde_json::to_string(items).unwrap()
}
#[cfg(not(feature = "json"))]
{
items.iter().map(|(n, c)| format!("{n}={c}")).collect::<Vec<_>>().join(",")
}
}
fn main() {
println!("{}", describe(&[("apples", 3), ("pears", 5)]));
println!("json feature on: {}", cfg!(feature = "json"));
}- Build or run with and without the feature.
> cargo run -q
apples=3,pears=5
json feature on: false
> cargo run -q --features json
[["apples",3],["pears",5]]
json feature on: trueWhy it works#
--features json makes Cargo pass --cfg 'feature="json"' to the compiler and build the optional dependency. Features are additive: if two crates in one build ask for different features of the same dependency, Cargo builds it once with all of them on. For that reason a feature should only add things, never change what existing code does.
Common mistakes#
- Making a feature that removes functionality (a
no-jsonfeature). Name the feature after what it adds. - Forgetting
default = [...]. Features listed there are on unless a user passes--no-default-features. - Guarding code with
#[cfg(feature = "json")]without declaringjsonunder[features]. The compiler then reports an unexpectedcfgcondition.
Related questions#
How do I turn on features of a dependency?#
Write them in the dependency line: serde = { version = "1", features = ["derive"] }.
How do I build with every feature on?#
cargo build --all-features. Use it in tests so every combination of your code gets compiled at least once.
In Ruststudio#
Ruststudio runs cargo for you, so a [features] table in Cargo.toml works as described here. The commands in the Run menu build with the features Cargo selects by default; for a feature that is off by default, run the command from the Terminal with --features.