rusttraits

How do you feature-gate trait derivation?


Lets say you got an enum like this:

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MyEnum {
    One,
    Two,
    Three,
    Four,
}

But you only want to derive, let's say PartialEq, if a certain feature (let's call it myenum-partialeq) is enabled.

How is this done idiomatically in Rust?


Solution

  • Use #[cfg_attr()]:

    #[derive(Debug, Clone, Copy)]
    #[cfg_attr(feature = "myenum-partialeq", derive(PartialEq))]
    pub enum MyEnum {
        One,
        Two,
        Three,
        Four,
    }
    

    One thing that is nice to remember, is to always put #[derive(Copy)] on the same line or above #[derive(Clone)] if the struct is not generic. This is because if #[derive(Clone)] is on the same #[derive()] or below #[derive(Copy)] it expands to just performing a bitwise copy, while if it is above it performs a full-fledged clone() for each field, and that takes time and may not even be possible to optimize.