Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created May 27, 2021 23:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewjberger/0e52a56b00c7df291a48826d3844c410 to your computer and use it in GitHub Desktop.
Save matthewjberger/0e52a56b00c7df291a48826d3844c410 to your computer and use it in GitHub Desktop.
Rust matches macro
/// Returns whether the given expression matches any of the given patterns.
///
/// Like in a `match` expression, the pattern can be optionally followed by `if`
/// and a guard expression that has access to names bound by the pattern.
///
/// # Examples
///
/// ```
/// let foo = 'f';
/// assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
///
/// let bar = Some(4);
/// assert!(matches!(bar, Some(x) if x > 2));
/// ```
macro_rules! matches {
($expression:expr, $( $pattern:pat )|+ $( if $guard: expr )? $(,)?) => {
match $expression {
$( $pattern )|+ $( if $guard )? => true,
_ => false
}
}
}
fn main() {
let foo = 'f';
assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment