What's your opinion about the `is_variant` pattern on enum?

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

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 enums:


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