rustconditional-compilation

How to use variable with #[cfg(...)] attribute?


I would like to use some code only in Debug mode for assertion purposes. I have something like this at the moment:

#[cfg(debug_assertions)]
let mut thing_initialized = false;

for ... {
    if cfg!(debug_assertions) {
        if expensive_check() { thing_initialized = true; }
    }
}

if cfg!(debug_assertions) {
    assert(thing_initialized);
}

But when the cfg is false, I get this error on all the lines thing_initialized is used on:

error[E0425]: cannot find value `thing_initialized` in this scope

What would be the right way to go about this? I could probably just write a proc macro and conditionally generate the expression from that, but seems like overkill. Is there a standard Rust method to achieve this? Or a common library that does the proc-macro thing already?


Solution

  • Instead of if cfg!(debug_assertions) below, just use #[cfg] on a block:

    #[cfg(debug_assertions)]
    let mut thing_initialized = false;
    
    for ... {
        #[cfg(debug_assertions)]
        {
            if expensive_check() { thing_initialized = true; }
        }
    }
    
    #[cfg(debug_assertions)]
    {
        assert(thing_initialized);
    }