Check if a vector of enums contains any enum of a type regardless the value

Hi!
Suppose that I have a vector or enums, some variants have fields and some don't. How do I check if a vector contains any variations of a specific enum field regardless of any value it might contain? For instance, in the following example, How do I check if spells contains Shield without knowing that the value of Shield is 10? Thanks

#[derive(Ord, PartialOrd, Eq, PartialEq, Hash)]
enum Spell {
    MagicMissile,
    Shield(i32), 
}

fn main() {
    let spells = vec![Spell::MagicMissile, Spell::Shield(10)];
    println!("{}", asd.contains(&Spell::MagicMissile));
    println!("{}", asd.contains(&Spell::Shield(0)));
    println!("{}", asd.contains(&Spell::Shield(10)));
}
spells.iter().any(|s| match s {
    Spell::Shield(_) => true,
    _ => false,
})

If you’re doing this a lot this might be helpful:
https://crates.io/crates/derive_is_enum_variant

2 Likes

And crate matches' macros are very nice to use as well.

https://crates.io/crates/matches

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.