Rollup merge of #52003 - Kerollmops:option-replace, r=Kimundi

Implement `Option::replace` in the core library

Here is the implementation of the `Option::replace` method. The first step of [the tracking issue #51998](https://github.com/rust-lang/rust/issues/51998).
This commit is contained in:
kennytm 2018-07-14 02:56:40 +08:00 committed by GitHub
commit a2c3713ea6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 43 additions and 0 deletions

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

View File

@ -44,6 +44,7 @@
#![feature(reverse_bits)]
#![feature(iterator_find_map)]
#![feature(slice_internals)]
#![feature(option_replace)]
extern crate core;
extern crate test;

View File

@ -297,3 +297,18 @@ fn test_try() {
}
assert_eq!(try_option_err(), Err(NoneError));
}
#[test]
fn test_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);
}