Skip to content

Commit

Permalink
Add Option::get_or_default
Browse files Browse the repository at this point in the history
  • Loading branch information
camsteffen committed Mar 8, 2021
1 parent 1d6b0f6 commit 7e3ebe7
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions library/core/src/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,34 @@ impl<T> Option<T> {
// Entry-like operations to insert if None and return a reference
/////////////////////////////////////////////////////////////////////////

/// Inserts the default value into the option if it is [`None`], then
/// returns a mutable reference to the contained value.
///
/// # Examples
///
/// ```
/// #![feature(option_get_or_default)]
///
/// let mut x = None;
///
/// {
/// let y: &mut u32 = x.get_or_default();
/// assert_eq!(y, &0);
///
/// *y = 7;
/// }
///
/// assert_eq!(x, Some(7));
/// ```
#[inline]
#[unstable(feature = "option_get_or_default", issue = "82901")]
pub fn get_or_default(&mut self) -> &mut T
where
T: Default,
{
self.get_or_insert_with(Default::default)
}

/// Inserts `value` into the option if it is [`None`], then
/// returns a mutable reference to the contained value.
///
Expand Down

0 comments on commit 7e3ebe7

Please sign in to comment.