Search code examples
rustbenchmarkingconditional-compilation

Rust Conditional flag set by Cargo bench


A function which is only being used with debug assertions is deactivated by:

#[cfg(debug_assertions)]
fn some_debug_support_fn() {}

But this makes cargo bench fail to compile, as it is missing the function implementation. How can I update the conditional to also be included in cargo bench?

I suspect cargo bench executes a binary on release profile and with debug info, but I couldn't confirm it. I was looking through the reference, and couldn't find anything relevant either.

Edit: Minimal reproducible example below:

#[cfg(debug_assertions)]
fn check_if_okay() -> bool {
    true
}

fn main() {

    debug_assert!(check_if_okay());
    
    println!("Minimal example!");
}

Solution

  • From the documentation of debug_assert!():

    The result of expanding debug_assert! is always type checked.

    To get the behavior you are looking for, you need your own explicit #[cfg(debug_assertions)] that controls compilation, not just whether the assertion is executed.

    #[cfg(debug_assertions)]
    assert!(check_if_okay());