1 | //! Pattern Matching macros. |
2 | |
3 | /// Returns true if an expression matches a pattern. |
4 | /// |
5 | /// # Example |
6 | /// |
7 | /// ``` |
8 | /// # #[macro_use ] extern crate mac; |
9 | /// |
10 | /// # fn main() { |
11 | /// assert!(matches!(2, 1 | 2 | 3)); |
12 | /// assert!(matches!('x' , 'a' ... 'z' )); |
13 | /// assert!(!matches!(Some(1), None)); |
14 | /// assert!(matches!(Some(42), Some(n) if n == 42)); |
15 | /// # } |
16 | /// ``` |
17 | #[macro_export ] |
18 | macro_rules! matches { |
19 | ($expr:expr, $($pat:tt)+) => { |
20 | _tt_as_expr_hack! { |
21 | match $expr { |
22 | $($pat)+ => true, |
23 | _ => false |
24 | } |
25 | } |
26 | } |
27 | } |
28 | |
29 | /// Work around "error: unexpected token: `an interpolated tt`", whatever that |
30 | /// means. (Probably rust-lang/rust#22819.) |
31 | #[doc (hidden)] |
32 | #[macro_export ] |
33 | macro_rules! _tt_as_expr_hack { |
34 | ($value:expr) => ($value) |
35 | } |
36 | |
37 | #[test ] |
38 | fn test_matches() { |
39 | let foo: Option<&str> = Some("-12" ); |
40 | assert!(matches!(foo, Some(bar) if |
41 | matches!(bar.as_bytes()[0], b'+' | b'-' ) && |
42 | matches!(bar.as_bytes()[1], b'0' ... b'9' ) |
43 | )); |
44 | } |
45 | |