Skip to content
Merged
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
44 changes: 37 additions & 7 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,36 @@ impl<T> Option<T> {
}
}

/// Inserts `value` into the option then returns a mutable reference to it.
///
/// If the option already contains a value, the old value is dropped.
///
/// # Example
///
/// ```
/// #![feature(option_insert)]
///
/// let mut opt = None;
/// let val = opt.insert(1);
/// assert_eq!(*val, 1);
/// assert_eq!(opt.unwrap(), 1);
/// let val = opt.insert(2);
/// assert_eq!(*val, 2);
/// *val = 3;
/// assert_eq!(opt.unwrap(), 3);
/// ```
#[inline]
#[unstable(feature = "option_insert", reason = "newly added", issue = "78271")]
pub fn insert(&mut self, value: T) -> &mut T {
*self = Some(value);

match self {
Some(v) => v,
// SAFETY: the code above just filled the option
None => unsafe { hint::unreachable_unchecked() },
}
}

/////////////////////////////////////////////////////////////////////////
// Iterator constructors
/////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -792,7 +822,7 @@ impl<T> Option<T> {
// Entry-like operations to insert if None and return a reference
/////////////////////////////////////////////////////////////////////////

/// Inserts `v` into the option if it is [`None`], then
/// Inserts `value` into the option if it is [`None`], then
/// returns a mutable reference to the contained value.
///
/// # Examples
Expand All @@ -811,12 +841,12 @@ impl<T> Option<T> {
/// ```
#[inline]
#[stable(feature = "option_entry", since = "1.20.0")]
pub fn get_or_insert(&mut self, v: T) -> &mut T {
self.get_or_insert_with(|| v)
pub fn get_or_insert(&mut self, value: T) -> &mut T {
self.get_or_insert_with(|| value)
}

/// Inserts a value computed from `f` into the option if it is [`None`], then
/// returns a mutable reference to the contained value.
/// Inserts a value computed from `f` into the option if it is [`None`],
/// then returns a mutable reference to the contained value.
///
/// # Examples
///
Expand All @@ -839,8 +869,8 @@ impl<T> Option<T> {
*self = Some(f());
}

match *self {
Some(ref mut v) => v,
match self {
Some(v) => v,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're changing this method anyway, might as well call insert:

match self {
    Some(v) => v,
    None => self.insert(f()),
}

(GitHub didn't let me add this as a change suggestion)

// SAFETY: a `None` variant for `self` would have been replaced by a `Some`
// variant in the code above.
None => unsafe { hint::unreachable_unchecked() },
Expand Down