How to use features in Cargo

Define and enable optional functionality in Rust projects using Cargo features via Cargo.toml and build flags.

Use features in Cargo by defining them in the [features] section of your Cargo.toml and enabling them via the --features flag or conditional compilation. Define feature groups and dependencies, then activate them during build or test commands.

[features]
default = ["std"]
std = []
advanced = ["std", "dep:regex"]

[dependencies]
regex = { version = "1.10", optional = true }

Enable features when building or testing:

cargo build --features advanced
cargo test --features std

Use conditional compilation in your code:

#[cfg(feature = "advanced")]
use regex;