Poulposaure
Poulposaure

Reputation: 15

Filter vector of enums by associated enum using iter() and filter()

I'm trying to filter a vector of enums by an associated value :

In my case, the enum is Item, which got 2 cases:

I want to filter a Vec of Item's by G to get a Vec of Group's. In short: from Vec<Item> I want Vec<Group>. I got this error : no field 0 on type &&Item (I tried putting * and **).

Am I doing something wrong ?

Rust playground : https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fd87bb6e80396d055653c438e894f41a

The code for reference :

#[derive(Debug, PartialEq, Eq)]
enum Item {
    G(Group),
    S(MetaSegment)
}

#[derive(Debug, PartialEq, Eq)]
struct Group {}

#[derive(Debug, PartialEq, Eq)]
struct MetaSegment {}

fn main() {
    let mut stuff = Vec::<Item>::new();
    
    stuff.push(Item::G(Group{}));
    stuff.push(Item::S(MetaSegment{}));
    stuff.push(Item::G(Group{}));
    
    stuff
        .iter()
        .filter(|e| matches!(e.0, Item::G(_)))
        .for_each(|e| println!("'{:#?}'", e));
}

Upvotes: 1

Views: 1384

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70990

You need to use matches!(e, Item::Group(_)) (without the .0).

However, it still produces an iterator over Items, not Groups. You want filter_map() instead:

stuff
    .iter()
    .filter_map(|e| match e {
        Item::G(group) => Some(group),
        _ => None,
    })
    .for_each(|e| println!("{:#?}", e));

Upvotes: 2

Related Questions