alekratz/enum-methods

Exclusion attributes

Opened this issue · 1 comments

Sometimes it is not desirable to generate a method for a variant of an enum. Presently, there is no way to skip over some specific element. I think we should add a per-element attribute that tells a given derive to skip that element. For example:

struct MyType;

#[derive(EnumToGetters, EnumAsGetters)]
enum MyEnum {
    #[enum_as_getters(skip)]
    Foo(i32), // EnumAsGetters will return a reference to this; we we override `as_foo()` below
    #[enum_to_getters(skip)]
    Bar(MyType), // MyType is not `Clone`, so EnumToGetters would fail to compile on this
}

impl MyEnum {
    pub fn as_foo(&self) -> i32 {
        if let &MyEnum::Foo(i) = self {
            *i
        }
        else { panic!( ... ) }
    }
}

This is also similar to how Serde works.

Some attributes that could be useful:

  • skip skips the tagged variant
  • rename = foo sets the generated getter name to foo
  • copy tells EnumToGetters to treat the variant's data like a Copy instead of a Clone