3

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?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
RBF06
  • 2,013
  • 2
  • 21
  • 20

1 Answers1

6

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.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • *About the derive note*: how weird... Usually, in Rust, the order of items / implementations / ... doesn't matter. Is it planned for `Clone` to be smarter about it? – jthulhu Jul 24 '22 at 19:11
  • @BlackBeans I think yes. The problem is that the compiler processes derives in order. This is not considererd a behavior change (although it can be observed), just an optimization. – Chayim Friedman Jul 24 '22 at 19:17