Feature Flags
Cargo features toggle optional dependencies and #[cfg(feature = "...")] code paths.
Busca en todas las páginas de la documentación
Cargo features toggle optional dependencies and #[cfg(feature = "...")] code paths.
[features]
default = ["std"]
std = []
json = ["dep:serde_json"]
[dependencies]
serde_json = { version = "1", optional = true }#[cfg(feature = "json")]
pub fn parse_json(s: &str) -> serde_json::Value {
serde_json::from_str(s).unwrap()
}When to reach for this: Optional integrations, no_std, compile-time trimming.
#[cfg(feature = "async")]
pub mod async_api;
#[cfg(not(feature = "async"))]
pub mod sync_api;Compile only one API surface per feature set.
What this demonstrates:
cfg attribute gates modulesdep:name (Cargo 1.60+)--no-default-features, --all-features for CI matrix. Feature unification in workspaces.
optional = true.cargo doc --all-features.| Alternative | Use When | Don't Use When |
|---|---|---|
| Separate crates | Large optional stacks | Small flag |
| Runtime config | User toggles at run | Compile-time trim needed |
cfg(target_os) | Platform code | Optional user feature |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026