If cfg!() but that actually do not include the code inside brackets if feature off?

I was using if cfg!() to simulate this type of stuff:

pub fn something(&self) {
    #[cfg(feature = "feature1")]

    #[cfg(not(feature = "feature1"))]

until I realized that if cfg!() does not hide the calls inside its {}, it's just a common if that has the true value hardcoded so on runtime it always picks the right one.

I could get away with doing as above, but what if I have 3 implementations per feature? What about 4? Then I'd have to put lots of #[cfg(and(not(feature = "feature1"), not(feature="feature2")))] and etc.

What would be the best solution in this case?

You might want the cfg_if macro. It's quite popular for this sort of use.


When enabling optimizations it won't even be compiled to a branch. The compiler will see that the branch always takes the same target and turns it into an unconditional jump that can then be eliminated. After that the now dead code for the unreachable case is deleted by the DCE optimization pass.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.