From 9553452cd99a764a5e4aef8f4c746617f8e647ca Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 11 May 2016 12:39:15 -0700 Subject: [PATCH] core: Add `Default::replace_default(&mut self)` --- src/libcore/default.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/libcore/default.rs b/src/libcore/default.rs index 12c4a5ca200a..f8ae8ba5b282 100644 --- a/src/libcore/default.rs +++ b/src/libcore/default.rs @@ -83,6 +83,7 @@ #![stable(feature = "rust1", since = "1.0.0")] use marker::Sized; +use mem; /// A trait for giving a type a useful default value. /// @@ -132,6 +133,38 @@ pub trait Default: Sized { /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn default() -> Self; + + /// Replace the value with the default and return the original value. + /// + /// # Examples + /// + /// Seamlessly take ownership of a vector: + /// + /// ``` + /// #![feature(replace_default)] + /// let mut x = vec![1, 2, 3]; + /// let y = x.replace_default(); + /// assert!(x.is_empty()); // empty, but still usable + /// assert_eq!(y.len(), 3); + /// ``` + /// + /// Extract and reset all values from a map: + /// + /// ``` + /// #![feature(replace_default)] + /// # use std::collections::HashMap; + /// # use std::hash::Hash; + /// fn take_values(map: &mut HashMap) -> Vec { + /// map.iter_mut().map(|(_, v)| { + /// v.replace_default() + /// }).collect() + /// } + /// ``` + #[inline] + #[unstable(feature = "replace_default", issue = "0")] + fn replace_default(&mut self) -> Self { + mem::replace(self, Default::default()) + } } macro_rules! default_impl {