Conditional non-compilation


#1

I want to define feature-a and feature-b, and force users to choose one of them,
failing to compile if none of them was defined.

So I came up with this:
if cfg!(feature = "feature-a") || cfg!(feature = "feature-b") { //some code here } else { //How do I fail here? }

So how do I fail compilation (ideally with usable message)?


#2

The cfg! macro is not conditional compilation. They return a boolean at compile-time and all the other code is compiled normally. What you want are cfg attributes:

#[cfg(any(feature = "feature-a", feature = "feature-b"))]
fn function_only_exists_when_features_are_active() {
}

if the features are not enabled, the function doesn’t exist and you get a compilation error.


#3

Thanks, I see that’s the only option (other then writing compiler plugin).


#4

Note that you can nest functions which might help make this look nicer if this is all local to a single function.