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;SerializeandDisplaycall this.impl Serialize— serialises theas_str()value.impl Deserialize— deserialises a JSON string using aVisitor; unknown values becomeOther(v.to_owned()).impl Display— formats theas_str()value, identical toSerialize.impl From<&str>andimpl From<String>— the same mapping asDeserialize, so a listed wire string always builds its typed variant and neverOther: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.