about summary refs log tree commit diff
diff options
context:
space:
mode:
authorKerollmops <renault.cle@gmail.com>2018-07-04 21:54:45 +0200
committerKerollmops <renault.cle@gmail.com>2018-07-04 21:54:45 +0200
commit603553458639cd65f3cc75b9b74f8176af81aa2b (patch)
tree18925003b1f5ce07d46119763fed47aecd27617b
parentb58b7219218f1862219e5d4d720174896f184989 (diff)
downloadrust-603553458639cd65f3cc75b9b74f8176af81aa2b.tar.gz
rust-603553458639cd65f3cc75b9b74f8176af81aa2b.zip
Implement `Option::replace` in the core library
-rw-r--r--src/libcore/option.rs27
1 files changed, 27 insertions, 0 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs
index 20bc173f7e1..db0a807d152 100644
--- a/src/libcore/option.rs
+++ b/src/libcore/option.rs
@@ -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> {