Skip to main content

EnumStr

Derive Macro EnumStr 

Source
#[derive(EnumStr)]
{
    // Attributes available to this derive:
    #[enum_str]
}
Expand description

Derive the EnumStr trait to convert between a unit enum and string.

EnumStr only supports unit enums (enums where all variants have no fields).

This macro generates:

  • impl EnumStr for T
  • impl From<T> for &'static str
  • impl AsRef<str> for T
  • impl FromStr for T
  • impl TryFrom<&str> for T
  • Error struct for invalid conversion from str

§Container attributes

  • #[enum_str(rename_all = "snake_case")]: rename all variants by rule
  • #[enum_str(alias_all = "lowercase")]: add aliases to all variants by rule (repeatable)
  • #[enum_str(default)]: fills non-unit variant’s fields with default value during parsing
  • #[enum_str(error_name = InvalidFoo)]: custom error type name (default: Invalid{Enum})
  • #[enum_str(error_msg = "…")]: custom error message template
  • #[enum_str(no_rendering)]: skip EnumStr, From, AsRef impls
  • #[enum_str(no_parsing)]: skip FromStr, TryFrom, and the error struct
  • #[enum_str(no_error_struct)]: skip the generated error struct (bring your own)

§Variant attributes

  • #[enum_str(rename = "custom_name")]: override the variant’s name
  • #[enum_str(alias = "alt")]: add an alias (repeatable)
  • #[enum_str(skip)]: skip variant, only affect parsing

§Available rename rules

  • lowercase
  • UPPERCASE
  • PascalCase
  • camelCase
  • snake_case
  • SCREAMING_SNAKE_CASE
  • kebab-case
  • SCREAMING-KEBAB-CASE

§Available error message template variables

  • {name}: the enum’s type name
  • {input}: the invalid input string (requires allocation)
  • {names}: all variant primary names
  • {aliases}: all names and aliases

List variables accept format modifiers:

  • {names}: default, comma-separated, double-quoted: "Bar", "Baz"
  • {names:|}: custom separator, no quotes: Bar|Baz
  • {names: - :'}: custom separator and quote char: 'Bar' - 'Baz'

Use {{ and }} for literal braces. : cannot be used as a separator or quote character.

§Example

use enum_helper::EnumStr;

#[derive(EnumStr, Debug, PartialEq, Eq)]
#[enum_str(rename_all = "lowercase")]
pub enum Foo {
    Bar,
    #[enum_str(alias = "bazzz")]
    Baz,
}

assert_eq!(Foo::Bar.as_name(), "bar");
assert_eq!("bazzz".parse::<Foo>().unwrap(), Foo::Baz);