Conditional compilation strangeness

I am trying to use conditional compilation according to the minimal example in
this playground link, which does not compile.

If I swap the two conditional blocks, the code compiles. It seems like the compiler doesn't see beyond the second conditional block if the first one is in use. Furthermore, if I remove the second conditional block, which is not being compiled in, it compiles - my understanding is that removing compiled-out blocks should have no impact.

Any explanation of this behavior and how to code around it would be great. My real code example can be found here.

Thanks!

I guess the conditional compilation attributes are not on blocks, but on expressions (or, more likely, on statements). So the second conditionally-compiled part in your playground is not this:

#[cfg(feature="foo")] {
    None
}

but rather this:

#[cfg(feature="foo")] {
    None
}

.unwrap_or_default()

If you wrap the whole conditionally-compiled part into another block, so that all expressions inside it terminate at the end of this block, like this:

let f: Foo = {
    {
        #[cfg(not(feature = "foo"))]
        {
            Some(Foo { bar: 1 })
        }

        #[cfg(feature = "foo")]
        {
            None
        }
    }
    .unwrap_or_default()
};

...the code compiles without problems.

1 Like

Thank you for the quick response. I understand now - I was equating the cfg blocks to ifdef/endif preprocessor macros when they are more like tags over the whole expression which follows.

Thanks.

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.