alekratz / enum-methods

Method generation for enumerated types in Rust
Apache License 2.0
12 stars 3 forks source link

Enum name getters #11

Open alekratz opened 7 years ago

alekratz commented 7 years ago

One problem we have with a lot of the getters is that they require derive(Debug), which is all well and good until you start working with weird types that aren't Debug (e.g. function pointers). Since Debug is only used to print out the name of the variant in the event of a panic, and not the data, I think it makes the most sense to generate methods which return a &'static str of its name. Then, Enum{As,Into,To}Getters would just use that generated name method to display in the panic!.

For example,

#[derive(EnumNames)]
enum MyEnum {
    Foo(i32),
    Bar(i64),
    Baz(String),
}

// generates
impl MyEnum {
    fn enum_names(&self) -> &'static str {
        match &self {
            &MyEnum::Foo(_) -> "Foo",
            &MyEnum::Bar(_) -> "Bar",
            &MyEnum::Baz(_) -> "Baz",
        }
    }
}

Gotchas: