Expand description
The Discriminant trait, along with its corresponding derive macro, offers a constant-time and safe method for extracting the primitive form of the discriminant value for enums.
The trait is derivable only when the following conditions are met:
-
The enum’s is accompanied by
#[repr(x)]attribute, wherexmust be one of the supported primitive types:u8,i8,u16,i16,u32,i32,u64, ori64. -
All enum variants have explicit discriminants.
-
Except for
#[repr(x)], there are no#[attr]style proc-macros after#[derive(Discriminant)].
§Usage
To use this macro, simply annotate your enum with #[derive(Discriminant)] as follows:
use safe_discriminant::Discriminant;
#[derive(Discriminant)]
#[repr(u8)]
enum Foo {
A = 1,
B(u8) = 2,
C{inner: u8} = 3,
}
let a = Foo::A;
let b = Foo::B(5);
let c = Foo::C{inner: 6};
assert_eq!(a.discriminant(), 1);
assert_eq!(b.discriminant(), 2);
assert_eq!(c.discriminant(), 3);Traits§
- Discriminant
Derive Macros§
- Discriminant
- Top level derive macro for
Discriminanttrait. For more information on how to use refer tosafe-discriminantcrate.