#proc #macro #derive #enum #fromstr

macro enum_from_str_derive

Enable deriving FromStr for enums

1 unstable release

0.1.0 Feb 5, 2019

#21 in #proc

Download history 16/week @ 2021-01-17 15/week @ 2021-01-24 8/week @ 2021-01-31 36/week @ 2021-02-07 25/week @ 2021-02-14 96/week @ 2021-02-21 57/week @ 2021-02-28 48/week @ 2021-03-07 116/week @ 2021-03-14 99/week @ 2021-03-21 27/week @ 2021-03-28 20/week @ 2021-04-04 74/week @ 2021-04-11 36/week @ 2021-04-18 42/week @ 2021-04-25 55/week @ 2021-05-02

175 downloads per month
Used in 3 crates

MIT license

3KB
52 lines

enum-from-str-rs

Allow derive FromStr for enums

Overview

This library adds the #[derive(FromStr)] attribute for enums, thus allowing parsing strings into enum variants. Even though there are other libraries that allows this, like enum_derive, it only allows you to parse from strings with the exact name of a variant. This library allows you to define a custom string for each enum variant.

Basic usage

use enum_from_str::ParseEnumVariantError;
use enum_from_str_derive::FromStr;

#[derive(FromStr)]
enum SomeEnum {
    #[from_str="foo"]
    Foo,
    Bar, // equals to #[from_str="Bar"]
}

fn example() {
    "foo".parse::<SomeEnum>().unwrap();
    "Bar".parse::<SomeEnum>().unwrap();
}

Known issues

Currently, proc-macro crates doesn't allow exporting anything other than the proc-macro function. That's why ParseEnumVariantError is in a different crate. When Rust allows it, it should be moved into a single crate.

Dependencies

~1.5MB
~42K SLoC