Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made matches! more useful by adding mapping support #79188

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion library/core/src/macros/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,10 @@ macro_rules! debug_assert_ne {
/// 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.
///
/// If the pattern is followed by a `=>` and a further mapping expression, an
/// [`Option`] will be produced, optionally containing the value produced by
/// evaluating the mapping expression in the context of the pattern.
///
/// # Examples
///
/// ```
Expand All @@ -229,6 +233,14 @@ macro_rules! debug_assert_ne {
///
/// let bar = Some(4);
/// assert!(matches!(bar, Some(x) if x > 2));
///
/// enum Baz {
/// A(bool),
/// B(i32),
/// }
///
/// let baz = Baz::A(true);
/// assert_eq!(matches!(baz, Baz::A(x) => !x), Some(false));
/// ```
#[macro_export]
#[stable(feature = "matches_macro", since = "1.42.0")]
Expand All @@ -238,7 +250,13 @@ macro_rules! matches {
$( $pattern )|+ $( if $guard )? => true,
_ => false
}
}
};
($expression:expr, $( $pattern:pat )|+ $( if $guard: expr )? $(,)? => $mapping:expr) => {
match $expression {
$( $pattern )|+ $( if $guard )? => $crate::option::Option::Some($mapping),
_ => $crate::option::Option::None
}
};
}

/// Unwraps a result or propagates its error.
Expand Down