Take_while on iterator of enums

Hi, I have an iterator whose Items are enums... I want to "take_while" on this iterator, until a specific enum variant is found (in my case, Action::BeginShift). Currently, I do:

for note in it.take_while(|n| match n.action {
    Action::BeginShift(_) => false,
    _ => true,
}) {


Howerver, I find this a bit verbose... Something like this would be nicer:

for note in it.take_while(|n| n.action == Action::BeginShift(_)) { }

But that's clearly not valid rust syntax. Can anyone recommend a more readable to way to "take_while" on an iterator of Enums, until a particular enum variant is reached?

My best solution for this is defining methods to do the comparison in one place, and then using those methods. Kind of like Result's is_ok and is_err, you could define:

impl Action {
    fn is_begin_shift(&self) -> bool {
        match self { Action::BeginShift(_) => true, _ => false }

Since this is fairly predictable, it can be automated. derive_is_enum_variant looks like a fairly light crate to do that.


Note that this kind of thing is also why we have Option::is_some and friends.

The matches crate has a macro that can replace your match expression.

1 Like

Thanks all, adding a method (or using a macro that does) is a nice solution that I didn't think of.