Skip to main content

impl_string_enum

Macro impl_string_enum 

Source
macro_rules! impl_string_enum {
    ($ty:ident, $expecting:literal, $( $s:literal => $variant:ident ),+ $(,)?) => { ... };
}
Expand description

Implement an inherent as_str(), serde::Serialize, serde::Deserialize, std::fmt::Display, From<&str> and From<String> for a string-backed enum with a catch-all Other(String) variant.

§Requirements

The enum must have a variant Other(String) that stores the raw wire string for any value not listed in the known-value mapping. The macro generates match arms only for the listed variants; the Other catch-all is generated automatically.

§Usage

ⓘ
impl_string_enum!(MyEnum, "a my-enum value",
    "wire-string-1" => Variant1,
    "wire-string-2" => Variant2,
);

This emits:

  • pub fn as_str(&self) -> &str — the single wire mapping: each listed variant yields its wire string, Other(v) yields the inner string. Do not hand-write a second copy; Serialize and Display call this.
  • impl Serialize — serialises the as_str() value.
  • impl Deserialize — deserialises a JSON string using a Visitor; unknown values become Other(v.to_owned()).
  • impl Display — formats the as_str() value, identical to Serialize.
  • impl From<&str> and impl From<String> — the same mapping as Deserialize, so a listed wire string always builds its typed variant and never Other: MyEnum::from("wire-string-1") == MyEnum::Variant1.

§Forged Other values

Other(String) is a public variant, so a caller can write MyEnum::Other("wire-string-1".into()). That value compares unequal to MyEnum::Variant1, yet serialises to the same wire string and deserialises back as MyEnum::Variant1. Build values from a string with MyEnum::from(..), which never yields Other for a listed wire string, and construct Other directly only for a string the enum does not list.