@@ -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