Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: Add Default::replace_default(&mut self) #33564

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/libcore/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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<K: Eq + Hash, V: Default>(map: &mut HashMap<K, V>) -> Vec<V> {
/// 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 {
Expand Down