cfg_attr

Config attribute attribute

// Note: `derive(PartialEq)` will be added only added for test.
#[derive(Debug)]
#[cfg_attr(
    test,              // condition(s)
    derive(PartialEq)  // attribute to be added when condition et
)] 
struct MyStruct {
  name: String, // some data
}

cfg_attr is a conditional compilation attribute that is used to conditionally include attributes based on a configuration option. It allows you to apply attributes based on compile-time flags, making it easier to write code that can change behavior depending on the configuration options that are set when the code is compiled.

Conditions can be more advanced with all(...) or any(...)

// Note: Derive(PartialEq) will be added only for test AND on macos.
#[derive(Debug)]
#[cfg_attr(
    all(test, target_os = "macos"), 
    derive(PartialEq)
)] 
struct MyStruct {
  name: String, // some data
}

Related links