Skip to content

Commit 6035534

Browse files
committed
Implement Option::replace in the core library
1 parent b58b721 commit 6035534

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/libcore/option.rs

+27
Original file line numberDiff line numberDiff line change
@@ -845,6 +845,33 @@ impl<T> Option<T> {
845845
pub fn take(&mut self) -> Option<T> {
846846
mem::replace(self, None)
847847
}
848+
849+
/// Replaces the actual value in the option by the value given in parameter,
850+
/// returning the old value if present,
851+
/// leaving a `Some` in its place without deinitializing either one.
852+
///
853+
/// [`Some`]: #variant.Some
854+
///
855+
/// # Examples
856+
///
857+
/// ```
858+
/// #![feature(option_replace)]
859+
///
860+
/// let mut x = Some(2);
861+
/// let old = x.replace(5);
862+
/// assert_eq!(x, Some(5));
863+
/// assert_eq!(old, Some(2));
864+
///
865+
/// let mut x = None;
866+
/// let old = x.replace(3);
867+
/// assert_eq!(x, Some(3));
868+
/// assert_eq!(old, None);
869+
/// ```
870+
#[inline]
871+
#[unstable(feature = "option_replace", issue = "51998")]
872+
pub fn replace(&mut self, value: T) -> Option<T> {
873+
mem::replace(self, Some(value))
874+
}
848875
}
849876

850877
impl<'a, T: Clone> Option<&'a T> {

0 commit comments

Comments
 (0)