Skip to content

Commit bab20b4

Browse files
authored
Rollup merge of #98935 - kellerkindt:option_retain, r=Mark-Simulacrum
Implement `Option::take_if` Tracking issue: #98934 ACP: rust-lang/libs-team#70 [accepted]
2 parents 2aae331 + 5419abd commit bab20b4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Diff for: library/core/src/option.rs

+35
Original file line numberDiff line numberDiff line change
@@ -1698,6 +1698,41 @@ impl<T> Option<T> {
16981698
mem::replace(self, None)
16991699
}
17001700

1701+
/// Takes the value out of the option, but only if the predicate evaluates to
1702+
/// `true` on a mutable reference to the value.
1703+
///
1704+
/// In other words, replaces `self` with `None` if the predicate returns `true`.
1705+
/// This method operates similar to [`Option::take`] but conditional.
1706+
///
1707+
/// # Examples
1708+
///
1709+
/// ```
1710+
/// #![feature(option_take_if)]
1711+
///
1712+
/// let mut x = Some(42);
1713+
///
1714+
/// let prev = x.take_if(|v| if *v == 42 {
1715+
/// *v += 1;
1716+
/// false
1717+
/// } else {
1718+
/// false
1719+
/// });
1720+
/// assert_eq!(x, Some(43));
1721+
/// assert_eq!(prev, None);
1722+
///
1723+
/// let prev = x.take_if(|v| *v == 43);
1724+
/// assert_eq!(x, None);
1725+
/// assert_eq!(prev, Some(43));
1726+
/// ```
1727+
#[inline]
1728+
#[unstable(feature = "option_take_if", issue = "98934")]
1729+
pub fn take_if<P>(&mut self, predicate: P) -> Option<T>
1730+
where
1731+
P: FnOnce(&mut T) -> bool,
1732+
{
1733+
if self.as_mut().map_or(false, predicate) { self.take() } else { None }
1734+
}
1735+
17011736
/// Replaces the actual value in the option by the value given in parameter,
17021737
/// returning the old value if present,
17031738
/// leaving a [`Some`] in its place without deinitializing either one.

0 commit comments

Comments
 (0)