Expand description
Macro for creating an enum where all variants have an associated constant string. Syntax:
str_enum::str_enum! {
#[phf] // Adds a PHF map
#[error_type(MyErrorType)] // Add this to opt-in to a FromStr implementation
#[derive(Clone, Copy)] // You can add derives (exceptions: de/serialize enable the `serde` feature for that, Hash which is implemented automatically to be compatible with &str since the type is Borrow<str>)
#[repr(u8)]
pub enum MyEnum {
Variant0 => "Value0"("other valid forms such as", "value0", "can go in brackets"), // note these other valid forms are only used in the enum's try_from_str method and FromStr implementation.
Variant1 = 3 => "Value1" // you can add a discriminant
}
}
let var0 = MyEnum::try_from_str("value0").unwrap();
assert_eq!(var0.as_str(), MyEnum::Variant0.as_str())Note, due to how we assemble some strings at compile time you’ll see some constants that you likely never need to interact with. You can just throw the enum in its own module to avoid seeing them since they’re private visibility.