Skip to content

How to conditionally include code in Rust debug builds

Posted on:December 12, 2024

You can use conditional compilation attributes (#[cfg(...)]) to conditionally include a field based on whether you’re building in debug mode. In typical Cargo-based Rust projects, the debug_assertions configuration predicate is enabled in debug builds and disabled in release builds.

Here’s an example:

#[derive(Debug)]
struct MyStruct {
    always_present: i32,
    
    #[cfg(debug_assertions)]
    debug_only: String,
}

How This Works:

Important Notes:

  1. Struct layout changes: Because the field is included only in debug builds, the memory layout of MyStruct changes between debug and release modes. If you rely on a stable binary interface (e.g., passing this struct across FFI boundaries), you need to ensure consistency. Usually, this isn’t a problem if you’re only using the struct internally.

  2. Derived trait implementations: If you have derived traits like Debug or Clone, they will also adapt accordingly. For Debug, it simply won’t print debug_only in release mode because the field isn’t there at all.

In summary, #[cfg(debug_assertions)] is the simplest and most idiomatic solution to conditionally include a field only in debug builds.