How to pull a dependency with different features under Cargo.toml "dependencies" and "dev-dependencies"?

2.3k views Asked by At

Suppose you have a dependency called "dep" which has two features called f1 and f2. I want to use "dep" with the f1 feature when I'm building my crate normally, but use it with f2 when building it for tests. I know dev-dependencies are those we need for tests and thought the following structure for Cargo.toml should work:

    [dev-dependencies]
    dep = { version = "1.0.0", features = ["f2"] }
    
    [dependencies]
    dep = { version = "1.0.0", features = ["f1"] }
    

However, it looks like once I have pulled in "dep" with "f1", the compiler would disregard the mention of the same dependency under the dev-dependencies section. On the other hand, making the dependency "optional" will not solve the issue because then "dep" will not be pulled in for the tests at all. Any ideas on how to resolve this issue or circumvent it nicely?

PS: I noticed the issue is being tracked here: https://github.com/rust-lang/cargo/issues/7916. So at the moment, I could only expect good workarounds from the respondents.

1

There are 1 answers

0
Alex jg On

This is possible with rust 2021 using resolver version 2. as documented here. Specifically it says this:

Features enabled on dev-dependencies will not be unified when those same dependencies are used as a normal dependency, unless those dev-dependencies are currently being built

In order to do this you will need your root package to have edition = "2021", then you can use resolver = "2" in your crate manifest to enable the desired behaviour.