How do I execute code based on the build type (release or debug)

So I need to execute code based on the build type (release or debug).
For example I need to call function A for release binaries and function B for debug binaries.
Essentially I'm just logging variables and events.

So far this is what I have:

#[cfg(debug_assertions)]
{
    println!("Config: {:#?}", config);
    println!("-------");
}

I have seen that some sources suggest using the log crate.
I really don't want to add unnecessary dependencies just to solve a simple problem.
So I'm asking for help here :smiley: :+1:

debug_assertions is usually good enough for normal cargo builds (unless custom profiles or build systems are used), you can use the cfg!() macro when used as statements in functions:

if cfg!(debug_assertions)] {
    println!("debug build");
} else {
    println!("release build");
}

The log crate itself wouldn't add this debug vs release functionality, instead, it just provides a "facade" that changes how and where it logs to.

Your current example, or @nerditation's example would work in the basic idea, however.

Why do you need this based on the build profile? Could you just have a --verbose flag in the CLI or similar?

Generally different code by build profile is asking for trouble since you then can't debug stuff any more.

1 Like

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.