Skip to content

Commit

Permalink
Rollup merge of rust-lang#52003 - Kerollmops:option-replace, r=Kimundi
Browse files Browse the repository at this point in the history
Implement `Option::replace` in the core library

Here is the implementation of the `Option::replace` method. The first step of [the tracking issue rust-lang#51998](rust-lang#51998).
  • Loading branch information
kennytm committed Jul 12, 2018
2 parents 10443c8 + c8f0e6f commit e2683f2
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/libcore/option.rs
Expand Up @@ -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> {
Expand Down
1 change: 1 addition & 0 deletions src/libcore/tests/lib.rs
Expand Up @@ -44,6 +44,7 @@
#![feature(reverse_bits)]
#![feature(iterator_find_map)]
#![feature(slice_internals)]
#![feature(option_replace)]

extern crate core;
extern crate test;
Expand Down
15 changes: 15 additions & 0 deletions src/libcore/tests/option.rs
Expand Up @@ -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);
}

0 comments on commit e2683f2

Please sign in to comment.