Skip to content

Add derive EnumCommonFields #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

dfaust
Copy link
Contributor

@dfaust dfaust commented Jan 17, 2017

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
Copy link
Owner

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
Copy link
Contributor Author

dfaust commented Feb 17, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants