How to Use Conditional Dependencies in Cargo

Add optional = true to dependencies in Cargo.toml and enable them via features or environment variables to conditionally include libraries.

Use the optional flag in your Cargo.toml dependencies and enable them via features or environment variables. Add optional = true to the dependency definition and reference it in a feature or conditional compilation block.

[dependencies]
serde = { version = "1.0", optional = true }

[features]
default = []
with-serde = ["serde"]

Enable the dependency by running cargo build --features with-serde or by setting RUSTFLAGS="--cfg feature=\"with-serde\"" for environment-based control.