Created
May 27, 2021 23:08
-
-
Save matthewjberger/0e52a56b00c7df291a48826d3844c410 to your computer and use it in GitHub Desktop.
Rust matches macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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