Skip to content

Derive EnumString

Peter Glotfelty edited this page Mar 20, 2020 · 2 revisions

auto-derives std::str::FromStr on the enum. Each variant of the enum will match on it's own name. This can be overridden using serialize="DifferentName" or to_string="DifferentName" on the attribute as shown below. Multiple deserializations can be added to the same variant. If the variant contains additional data, they will be set to their default values upon deserialization.

The default attribute can be applied to a tuple variant with a single data parameter. When a match isn't found, the given variant will be returned and the input string will be captured in the parameter.

Here is an example of the code generated by deriving EnumString.

use strum;
use strum_macros::EnumString;
use std::str::FromStr;

#[derive(EnumString)]
enum Color {
    Red,

    // The Default value will be inserted into range if we match "Green".
    Green { range:usize },

    // We can match on multiple different patterns.
    #[strum(serialize="blue",serialize="b")]
    Blue(usize),

    // Notice that we can disable certain variants from being found
    #[strum(disabled="true")]
    Yellow,
}

/*
//The generated code will look like:
impl std::str::FromStr for Color {
    type Err = ::strum::ParseError;

    fn from_str(s: &str) -> ::std::result::Result<Color, Self::Err> {
        match s {
            "Red" => ::std::result::Result::Ok(Color::Red),
            "Green" => ::std::result::Result::Ok(Color::Green { range:Default::default() }),
            "blue" | "b" => ::std::result::Result::Ok(Color::Blue(Default::default())),
            _ => ::std::result::Result::Err(::strum::ParseError::VariantNotFound),
        }
    }
}
*/

pub fn main() {
    let color_variant = Color::from_str("Red").unwrap();
    assert!(Color:Red, color_variant);
}

Note that the implementation of FromStr by default only matches on the name of the variant. There is an option to match on different case conversions through the #[strum(serialize_all = "snake_case")] type attribute. See the Additional Attributes Section for more information on using this feature.

Clone this wiki locally