VP.
VP.

Reputation: 16705

How can I make two features enabled lead to a conflict in Rust?

I have two features: feature_1 and feature_2:

[features]
default = ["feature_1"]
feature_1 = []
feature_2 = []

I want to let the user choose only one of them at a time because choosing both at the same time will lead to a duplicating of some important code and by some other reasons. How can I do that?

Upvotes: 6

Views: 1958

Answers (2)

Ithinuel
Ithinuel

Reputation: 166

For what it's worth, I opted to use this approach:

#[cfg(all(feature = "feature_1", feature = "feature_2"))]
compile_error!("Feature 1 and 2 are mutually exclusive and cannot be enabled together");

I hope it'll help others looking for a solution to the same problem.

Upvotes: 13

DK.
DK.

Reputation: 59015

Fundamentally, you can't. Cargo features are additive, and features can be enabled by any crate in the dependency tree. There's an implicit assumption on the part of Cargo that it is always valid to enable additional features.

What's more, features aren't simply requests, they are demands. If one crate demands feature_1, and another crate demands feature_2, you've got two crates that cannot possibly work together. Cargo (and Rust itself) go to some lengths to try and make such situations difficult to create.

The best solution is to change how your crate is written such that both features can be enabled simultaneously. If that's really impossible, the best you can do is prevent compilation from succeeding. This can be done either with a build script for your crate that detects incompatible features and fails, or by placing non-compiling code in your crate that is only enabled when incompatible features are enabled.

Upvotes: 4

Related Questions