Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cargo.toml: how do I select a dependency's feature based on my crate's features? [duplicate]

The scenario is the following: my crate has a dependency on num-bigint, and an optional dependency on rand:

[dependencies]
num-bigint = { version = "0.2" }
rand = { version = "0.7", optional = true }

When rand is disabled on my crate, everything's fine.

When rand is enabled on my crate, I would like the rand feature of num-bigint to be enabled as well. How can I do that?

Here's what I tried:

[target.'cfg(feature = "rand")'.dependencies]
num-bigint = { version = "0.2", features = ["rand"] }

This works, but I'm receiving this warning:

warning: Found `feature = ...` in `target.'cfg(...)'.dependencies`. This key is not supported for selecting dependencies and will not work as expected. Use the [features] section instead: https://doc.rust-lang.org/cargo/reference/features.html

Should I just ignore the warning, or is there a better way to do it? I checked that web page, but I cannot find anything helpful.

like image 902
prosc Avatar asked Jan 01 '26 01:01

prosc


1 Answers

You can use "crate/feature" in your features (as described in the Cargo documentation) to specify which features of dependencies that should be enabled:

[features]
enable-rand = ["rand", "num-bigint/rand"]

Note that the feature needs to have a name that does not conflict with the name of a dependency, as optional dependencies create implicit features, and you cannot set those to enable other features this way. (The implementation of this functionality is being tracked in Cargo issue #5565, if you're interested.)

like image 166
Frxstrem Avatar answered Jan 04 '26 06:01

Frxstrem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!