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

1

10

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.

Bloodthirsty answered 7/4, 2020 at 22:18 Comment(0)
C
14

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.)

Clubhaul answered 7/4, 2020 at 22:32 Comment(4)
That fails with: Features and dependencies cannot have the same name: `rand`Bloodthirsty
@Bloodthirsty Yes, I've updated the answer with some more details around that.Clubhaul
Mh, so there's no way to do that without renaming the feature? That would be a big inconvenience for meBloodthirsty
@Bloodthirsty Yes, as I've mentioned in my answer it's a feature in the works, but currently it's not possible to do.Clubhaul

© 2022 - 2024 — McMap. All rights reserved.