Is it possible to conditionally enable an attribute like `derive`?

You can use the cfg_attr(a, b) attribute:

#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct MyStruct;

It’s described in the Rust reference about “conditional compilation”:

#[cfg_attr(a, b)]
item

Will be the same as #[b] item if a is set by cfg, and item otherwise.

Leave a Comment