domains / / tokio-rs/tokio
Structure feature flags strategically
Design feature flags to minimize dependency bloat while maximizing flexibility for users. Each optional dependency should be tied to a specific feature flag, allowing users to enable only the functionality they need.
Design feature flags to minimize dependency bloat while maximizing flexibility for users. Each optional dependency should be tied to a specific feature flag, allowing users to enable only the functionality they need.
Key practices:
- Express dependencies between features explicitly in Cargo.toml
- Create granular feature flags for optional dependencies
- Use conditional compilation for platform or feature-specific code
- Consider feature organization when adding new functionality
For example, instead of requiring a dependency for all users:
# Avoid this approach - forces dependency on all users
rt = ["tokio/rt", "tokio/sync", "futures-util", "hashbrown"]
Use a more targeted approach:
# Better approach - separate optional functionality
rt = ["tokio/rt", "tokio/sync", "futures-util"]
join-map = ["rt", "hashbrown"]
For platform-specific features, use appropriate conditional compilation:
# For platform-specific features
[target.'cfg(all(target_os = "linux", feature = "rt"))'.dependencies]
# Linux-specific dependencies here
When organizing features, aim for a balance between granularity and usability, with a “full” feature that enables everything for convenience.