Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean expression for checking if expression matches pattern in Rust

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(_))))
like image 999
Marcel Avatar asked Apr 24 '26 06:04

Marcel


1 Answers

There's a macro named matches! for that!

vector.filter(|item| matches!(item, Some(Kind::B(_))))
like image 176
Marcel Avatar answered Apr 29 '26 23:04

Marcel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!