Lolirofle / enum_traits

Simple traits and derives for enums in the Rust programming language
MIT License
6 stars 5 forks source link

Add derive EnumCommonFields #4

Open dfaust opened 7 years ago

dfaust commented 7 years ago

This is not a trait, so I can understand if you don't want to merge it but I think it fits here best.

Using #[derive(EnumCommonFields)] on enums containing exclusively struct variants will implement member functions for all struct fields with the same name and type.

Examples:

#[derive(Debug, EnumCommonFields)]
enum Enum {
    Cat{age: u32},
    Dog{age: u32},
    Robot{age: u32},
}
assert_eq!(Enum::Dog{age: 3}.age(), &3);
#[derive(Debug, PartialEq, EnumCommonFields)]
enum Enum {
    Cat{age: u32},
    Dog{age: u32},
    Robot{age: u32},
}
let mut d = Enum::Dog{age: 3};
*d.age_mut() = 5;
assert_eq!(d, Enum::Dog{age: 5});
Lolirofle commented 7 years ago

This would not work on an enum like the following, right?

#[derive(Debug, EnumCommonFields)]
enum Enum {
    Cat{age: u32},
    Dog{age: u32},
    Robot,
}
assert_eq!(Enum::Dog{age: 3}.age(), Some(&3));
assert_eq!(Enum::Robot.age(), None);

I thought that maybe it would be more useful in those cases, but perhaps you have already found it useful like this?

dfaust commented 7 years ago

I think both cases are useful, it's just that I needed the non-optional version. The non-optional version has the advantage, that if you already know, that all enum variants share a common field, you won't have to care about unwrapping. Maybe it could be changed to something like #[derive(EnumField="age")] and it could be automatically determined whether it should return a value or an option.