Skip to content

Add the convenience method Option::is_some_and #75298

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

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
29 changes: 29 additions & 0 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,35 @@ impl<T> Option<T> {
!self.is_some()
}

/// Returns `true` if the option is a [`Some`] and the given predicate
/// returns `true` for the contained value.
///
/// # Examples
///
/// ```
/// #![feature(option_is_some_and)]
///
/// let x: Option<u32> = Some(2);
/// assert_eq!(x.is_some_and(|&n| n == 9), false);
/// assert_eq!(x.is_some_and(|&n| n < 5), true);
///
/// let x: Option<u32> = None;
/// assert_eq!(x.is_some_and(|&n| n == 9), false);
/// assert_eq!(x.is_some_and(|&n| n < 5), false);
/// ```
#[must_use]
#[inline]
#[unstable(feature = "option_is_some_and", issue = "none")]
pub fn is_some_and<P>(&self, predicate: P) -> bool
where
P: FnOnce(&T) -> bool,
{
match self {
Some(x) => predicate(x),
None => false,
}
}

/// Returns `true` if the option is a [`Some`] value containing the given value.
///
/// # Examples
Expand Down