| name | rust-features |
| description | Work with Cargo features and conditional compilation. Use when adding optional dependencies, using #[cfg(feature = "...")], conditional compilation, or organizing optional functionality. Handles feature flags, optional dependencies, and cfg attributes. |
Cargo Features and Conditional Compilation
Guidelines for working with Cargo features and conditional compilation in Rust.
When to Use This Skill
- Adding optional functionality
- Using
#[cfg(feature = "...")] attributes
- Organizing optional dependencies
- Conditional compilation based on features
- Creating feature gates for functionality
Defining Features in Cargo.toml
Basic Feature
[features]
default = []
gpu = []
Feature with Dependencies
[features]
default = []
gpu = ["burn", "burn_cubecl"]
[dependencies]
ndarray = { workspace = true }
burn = { version = "0.14", optional = true }
burn_cubecl = { version = "0.14", optional = true }
Default Features
[features]
default = ["gpu"]
gpu = []
Using #[cfg(feature = "...")]
Conditional Module
#[cfg(feature = "gpu")]
pub mod gpu;
#[cfg(feature = "gpu")]
pub use gpu::GpuMatrixOps;
Conditional Function
#[cfg(feature = "gpu")]
pub fn gpu_function() -> Result<()> {
Ok(())
}
#[cfg(not(feature = "gpu"))]
pub fn gpu_function() -> Result<()> {
Err(Error::GpuNotAvailable)
}
Conditional Implementation
#[cfg(feature = "gpu")]
impl GpuOps for MyStruct {
fn gpu_method(&self) -> Result<()> {
Ok(())
}
}
Conditional Benchmark
#[cfg(feature = "gpu")]
fn bench_gpu(c: &mut Criterion) {
}
#[cfg(not(feature = "gpu"))]
criterion_group!(benches, bench_cpu_only);
#[cfg(feature = "gpu")]
criterion_group!(
benches,
bench_cpu_only,
bench_gpu,
bench_comparison
);
Common Patterns
Feature-Gated API
#[cfg(feature = "gpu")]
pub struct GpuMatrixOps {
}
#[cfg(feature = "gpu")]
impl GpuMatrixOps {
pub fn new() -> Self {
}
pub fn is_available() -> bool {
}
}
Fallback Implementation
#[cfg(feature = "gpu")]
pub fn matrix_multiply(a: &Matrix, b: &Matrix) -> Result<Matrix> {
if GpuOps::is_available() {
gpu_multiply(a, b)
} else {
cpu_multiply(a, b)
}
}
#[cfg(not(feature = "gpu"))]
pub fn matrix_multiply(a: &Matrix, b: &Matrix) -> Result<Matrix> {
cpu_multiply(a, b)
}
Conditional Compilation in Tests
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_basic() {
}
#[cfg(feature = "gpu")]
#[test]
fn test_gpu() {
}
}
Feature Detection at Runtime
#[cfg(feature = "gpu")]
pub fn try_gpu_operation() -> Option<Result<()>> {
if GpuOps::is_available() {
Some(gpu_operation())
} else {
None
}
}
Multiple Features
Feature Combinations
#[cfg(all(feature = "gpu", feature = "cuda"))]
pub mod cuda_gpu;
#[cfg(any(feature = "gpu", feature = "opencl"))]
pub mod gpu_common;
Feature Exclusions
#[cfg(all(feature = "gpu", not(feature = "cpu-only")))]
pub fn gpu_function() {
}
Important Rules
- Use features for optional functionality: Don't use features for different implementations of the same API
- Document features: Add
#![doc(cfg(feature = "..."))] to document feature-gated items
- Default features: Be careful with default features - they're always enabled unless explicitly disabled
- Optional dependencies: Mark optional dependencies with
optional = true in Cargo.toml
- Feature combinations: Use
all(), any(), and not() for complex feature logic
- Runtime checks: Use runtime checks when feature availability needs to be detected at runtime
Documenting Features
#[cfg(feature = "gpu")]
#[doc(cfg(feature = "gpu"))]
pub mod gpu;
Building with Features
cargo build
cargo build --features gpu
cargo build --no-default-features
cargo build --features "gpu,cuda"
cargo test --features gpu
cargo bench --features gpu
Examples from Project
See fcs/Cargo.toml and fcs/src/gpu/ for examples of:
- Feature definitions
- Optional dependencies
- Conditional compilation
- Feature-gated modules
Common Patterns
✅ Good
[features]
default = []
gpu = ["burn"]
[dependencies]
burn = { version = "0.14", optional = true }
#[cfg(feature = "gpu")]
pub mod gpu;
❌ Avoid
[features]
everything = []
nothing = []
#[cfg(feature = "v1")]
pub fn api() {}
#[cfg(feature = "v2")]
pub fn api() {}