Skip to content

Commit 5d7909a

Browse files
committed
Added mapping support to matches!
1 parent 8d2d001 commit 5d7909a

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

library/core/src/macros/mod.rs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,10 @@ macro_rules! debug_assert_ne {
221221
/// Like in a `match` expression, the pattern can be optionally followed by `if`
222222
/// and a guard expression that has access to names bound by the pattern.
223223
///
224+
/// If the pattern is followed by a `=>` and a further mapping expression, an
225+
/// [`Option`] will be produced, optionally containing the value produced by
226+
/// evaluating the mapping expression in the context of the pattern.
227+
///
224228
/// # Examples
225229
///
226230
/// ```
@@ -229,6 +233,14 @@ macro_rules! debug_assert_ne {
229233
///
230234
/// let bar = Some(4);
231235
/// assert!(matches!(bar, Some(x) if x > 2));
236+
///
237+
/// enum Baz {
238+
/// A(bool),
239+
/// B(i32),
240+
/// }
241+
///
242+
/// let baz = Baz::A(true);
243+
/// assert_eq!(matches!(baz, Baz::A(x) => !x), Some(false));
232244
/// ```
233245
#[macro_export]
234246
#[stable(feature = "matches_macro", since = "1.42.0")]
@@ -238,7 +250,13 @@ macro_rules! matches {
238250
$( $pattern )|+ $( if $guard )? => true,
239251
_ => false
240252
}
241-
}
253+
};
254+
($expression:expr, $( $pattern:pat )|+ $( if $guard: expr )? $(,)? => $mapping:expr) => {
255+
match $expression {
256+
$( $pattern )|+ $( if $guard )? => $crate::option::Option::Some($mapping),
257+
_ => $crate::option::Option::None
258+
}
259+
};
242260
}
243261

244262
/// Unwraps a result or propagates its error.

0 commit comments

Comments
 (0)