Search code examples
rustdependenciesrust-cargo

Cargo.toml: how to conditionally enable a dependency feature?


In my project, I have 2 features: myfeatureA and myfeatureB.

I want one of them to depend on tokio with features rt and sync, and the other to depend on tokio with only the feature sync.

I tried this configuration in Cargo.toml:

[dependencies]
tokio = { version = "1.32", features = ["rt", "sync"], optional = true }

[features]
myfeatureA = ["dep:tokio"]
myfeatureB = ["dep:tokio/sync"]
$ cargo build --features=myfeatureB
error: failed to parse manifest at `[...]/myproject/Cargo.toml`

Caused by:
  feature `myfeatureB` includes `dep:tokio/sync` with both `dep:` and `/`
  To fix this, remove the `dep:` prefix.

So, I removed the dep: prefix (this is the solution provided by this other question, but it does not work):

[features]
myfeatureA = ["dep:tokio"]
myfeatureB = ["tokio/sync"]
$ cargo build --features=myfeatureB
error: Package `myproject v0.1.0 ([...]/myproject)` does not have feature `tokio`. It has an optional dependency with that name, but that dependency uses the "dep:" syntax in the features table, so it does not have an implicit feature with that name.

How can I make myfeatureB depend on tokio with only the sync feature?


Solution

  • This was reported in issue #10788, which was fixed for Rust 1.72.0. Now you can use the second approach (no dep:).

    For previous versions, don't use dep: at all, even for other features. This creates a feature named tokio, though.