Search code examples
rustpattern-matchingmatching

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(_))))

Solution

  • There's a macro named matches! for that!

    vector.filter(|item| matches!(item, Some(Kind::B(_))))