What's your pros/cons/opinion about providing is_variant
methods on simple enums ?
enum MyEnum {
Foo,
Goo,
Hoo,
}
impl MyEnum {
#[inline]
fn is_foo(&self) -> bool {
matches!(self, Self::Foo)
}
#[inline]
fn is_goo(&self) -> bool {
matches!(self, Self::Goo)
}
#[inline]
fn is_hoo(&self) -> bool {
matches!(self, Self::Hoo)
}
}
Personally, Iād lean towards #[derive(Eq,PartialEq)]
instead in most cases.
6 Likes
jjpe
July 16, 2022, 11:09am
3
For simple enums I agree with @2e71828 . For enum variants carrying data however, I think such predicates have definite use, e.g. in iterator method chains.
3 Likes
For what is worth, std
does define such methods on its most used enum
s:
Personally, I generally don't define such methods and rely more on ==
like @2e71828 , or on if let
.
When I do define such methods if for groups of variants that I often want to match together. A dumb example is the following:
enum HowMany {
One,
Two,
Three,
}
impl HowMany {
fn is_many(&self) -> bool {
matches!(self, Self::Two | Self::Three)
}
}
So I don't have to always match explicitly on both variants.
6 Likes
system
Closed
October 14, 2022, 11:18am
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.