Is it possible to convert a string to an enumeration without macros in Rust?

For example, if I have code like:

enum Foo {
    Bar,
    Baz,
    Bat,
    Quux
}

impl Foo {
    from(input: &str) -> Foo {
        Foo::input
    }
}

This obviously will not work, because it is inputnot a Foo method. I can manually type:

from(input: &str) -> Foo {
    match(input) {
        "Bar" => Foo::Bar,
        // and so on...
    }
}

but I do not get automatic convenience.

It seems that Java has a function for finding strings in enums for this specific purpose.

Is it possible to get this without writing my own macro or importing from a box?

+4
source share
1 answer

You can use boxes enum_deriveand custom_derivedo what you want.

Here is an example:

#[macro_use]
extern crate custom_derive;
#[macro_use]
extern crate enum_derive;

custom_derive! {
    #[derive(Debug, EnumFromStr)]
    enum Foo {
        Bar,
        Baz,
        Bat,
        Quux
    }
}

fn main() {
    let variable: Foo = "Bar".parse().unwrap();
    println!("{:?}", variable);
}

derive EnumFromStr parse Foo.

+9

Source: https://habr.com/ru/post/1651977/


All Articles