JohnT
JohnT

Reputation: 63

How to have an optional dependency enable another optional dependency rust

I am creating a library in rust and I have different features which the user can enable via optional dependencies. I want it so if the dependency diesel is enabled than diesel-derive-enum should also be enabled.

[dependencies]
diesel = {version = "1.4.6", optional = true, features = ["postgres", "chrono"]}
diesel-derive-enum = {version = "1.1.1", optional = true, features = ["postgres"]}

Upvotes: 5

Views: 5561

Answers (2)

Anders Evensen
Anders Evensen

Reputation: 881

As of Rust 1.60.0, with the stabilization of namespaced dependencies, you can now do this without having to add a differently named feature, using dep: features.

[dependencies]
diesel = {version = "1.4.6", optional = true, features = ["postgres", "chrono"]}
diesel-derive-enum = {version = "1.1.1", optional = true, features = ["postgres"]}

[features]
diesel = ["dep:diesel", "dep:diesel-derive-enum"]

Now you can simply pass --features diesel to cargo to enable both the diesel and diesel-derive-enum optional dependencies.

See the Cargo Book's section on Optional Features for more details.

Upvotes: 11

Edward Fitz Abucay
Edward Fitz Abucay

Reputation: 483

You can use cargo features to enable multiple optional dependencies.

Here is an example:

[dependencies]
cli-color = { version = "0.1.20", optional = true }
clap= { version = "0.2.3", optional = true }

[features]
cli = ["cli-color", "clap"]

Also a real world example coming from tokio. https://github.com/tokio-rs/tokio/blob/master/tokio/Cargo.toml

For more details see official rust docs: https://doc.rust-lang.org/cargo/reference/features.html#the-features-section

Upvotes: 1

Related Questions