Skip to main content

EnumFromName

Derive Macro EnumFromName 

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

Derives constructor lookup methods to instantiate unit enum variants from string names.

This macro implements two lookup methods on the enum:

  • pub fn from_name(name: &str) -> Option<Self>: Matches against the formatted variant name (respecting rename_all casing rules and rename overrides).
  • pub fn from_raw_name(name: &str) -> Option<Self>: Matches strictly against the original Rust variant identifier name.

Additionally, when the from-str feature is enabled (default), it generates an implementation of core::str::FromStr that parses formatted variant names by delegating to from_name().

§Attributes

  • #[enuminfo(rename_all = "...")]: Container attribute setting variant lookup keys using serde-compatible casing options.
  • #[enuminfo(rename = "custom_name")]: Variant attribute overriding the lookup key for from_name().
  • #[enuminfo(ignore_from_name)]: Variant attribute excluding the variant from both from_name() and from_raw_name() (and consequently from FromStr).

§Compile-Time Checks

Validates at compile time that all formatted variant lookup keys are unique. If duplicates occur, compilation fails with an error.

§Limitations

This macro supports Unit Enums only. Variants must have no data fields:

  • Unit variants (e.g. Variant)
  • Empty tuple variants (e.g. Variant())
  • Empty struct variants (e.g. Variant {})

Variants with fields will cause a compilation error.

§Feature Flags

  • from-str (default): Generates impl std::str::FromStr for MyEnum.
  • impl-enuminfo: Implements the enuminfo::EnumFromName trait for the enum.

§Example

use enuminfo_macros::EnumFromName;

#[derive(Debug, PartialEq, EnumFromName)]
#[enuminfo(rename_all = "lowercase")]
enum Priority {
    Low,
    High,
    #[enuminfo(ignore_from_name)]
    Critical,
}

// Formatted lookup
assert_eq!(Priority::from_name("low"), Some(Priority::Low));

// Raw identifier lookup
assert_eq!(Priority::from_raw_name("Low"), Some(Priority::Low));

// Ignored variants cannot be constructed by name
assert_eq!(Priority::from_name("critical"), None);
assert_eq!(Priority::from_raw_name("Critical"), None);