Reputation: 499
I have a Rust utility package containing different functionality separated via features (to provide only the specific functionality based on the need). The features have different dependencies which should be listed in Cargo.toml
of the utility package. Is there a way to add dependencies in a way that it would be included only if the user of the package requires the specific feature (i.e. eliminate compilation of the dependencies if the feature is not used)?
Upvotes: 3
Views: 5180
Reputation: 499
To enable conditional compilation of dependencies based on used features, there is a need to mark the dependency declaration as 'optional = true', then create a new feature combining all the used dependencies. E.g. if we have a feature - f1 and only it in the package depends on 'rand' & 'anyhow', there is a need to mark dependencies as optional and include them as a part of the feature:
[dependencies]
anyhow = { version = "1.0", optional = true }
rand = { version = "0.8", optional = true }
[features]
f1 = [anyhow, rand]
Upvotes: 7