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 serde::Serialize, serde::Deserialize, and std::fmt::Display 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:

  • impl Serialize — serialises each listed variant to its wire string; Other(v) serialises to the inner string.
  • impl Deserialize — deserialises a JSON string using a Visitor; unknown values become Other(v.to_owned()).
  • impl Display — formats using the same mapping as Serialize.