alekratz/enum-methods

Enum name getters

Opened this issue · 0 comments

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:

  • This would require exactly one instance of enum_name() to be generated. It may be difficult to keep track of when we're mixing and matching Enum*Getters because they are not aware of each other.
  • The above means we probably can't automatically derive from it, and it would become some extra boilerplate for users of the library to include, which I'm not a big fan of.