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