Implement Option::replace in the core library

This commit is contained in:
Kerollmops 2018-07-04 21:54:45 +02:00
parent b58b721921
commit 6035534586
No known key found for this signature in database
GPG Key ID: 016ACC0DC3ADC318

View File

@ -845,6 +845,33 @@ impl<T> Option<T> {
pub fn take(&mut self) -> Option<T> {
mem::replace(self, None)
}
/// Replaces the actual value in the option by the value given in parameter,
/// returning the old value if present,
/// leaving a `Some` in its place without deinitializing either one.
///
/// [`Some`]: #variant.Some
///
/// # Examples
///
/// ```
/// #![feature(option_replace)]
///
/// let mut x = Some(2);
/// let old = x.replace(5);
/// assert_eq!(x, Some(5));
/// assert_eq!(old, Some(2));
///
/// let mut x = None;
/// let old = x.replace(3);
/// assert_eq!(x, Some(3));
/// assert_eq!(old, None);
/// ```
#[inline]
#[unstable(feature = "option_replace", issue = "51998")]
pub fn replace(&mut self, value: T) -> Option<T> {
mem::replace(self, Some(value))
}
}
impl<'a, T: Clone> Option<&'a T> {