mirror of
https://github.com/rust-lang/rust.git
synced 2025-05-14 02:49:40 +00:00
Implement Option::replace
in the core library
This commit is contained in:
parent
b58b721921
commit
6035534586
@ -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> {
|
||||
|
Loading…
Reference in New Issue
Block a user