I have a Vec of values and want to filter those that match a certain pattern.
What is the idiomatic way to just check if an expression matches a pattern, without necessarily doing something with the match?
enum Kind {
A,
B(char),
}
let vector: Vec<Option<Kind>> = ...;
vector.filter(|item| /* check if item matches pattern Some(Kind::B(_)) */)
I know I can use the match keyword:
vector.filter(|item| match item {
Some(Kind::B(_)) => true,
_ => false,
})
or the if let keyword:
vector.filter(|item| {
if let Some(Kind::B(_)) = item {
true
} else {
false
}
})
But in both examples, the code still looks bulky because I manually need to provide the true and false constants.
I feel like there should be a more elegant way to do that, something similar to the following:
vector.filter(|item| matches(item, Some(Kind::B(_))))
There's a macro named matches! for that!
vector.filter(|item| matches!(item, Some(Kind::B(_))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With