Skip to content

Commit 7e3ebe7

Browse files
committed
Add Option::get_or_default
1 parent 1d6b0f6 commit 7e3ebe7

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

library/core/src/option.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,34 @@ impl<T> Option<T> {
854854
// Entry-like operations to insert if None and return a reference
855855
/////////////////////////////////////////////////////////////////////////
856856

857+
/// Inserts the default value into the option if it is [`None`], then
858+
/// returns a mutable reference to the contained value.
859+
///
860+
/// # Examples
861+
///
862+
/// ```
863+
/// #![feature(option_get_or_default)]
864+
///
865+
/// let mut x = None;
866+
///
867+
/// {
868+
/// let y: &mut u32 = x.get_or_default();
869+
/// assert_eq!(y, &0);
870+
///
871+
/// *y = 7;
872+
/// }
873+
///
874+
/// assert_eq!(x, Some(7));
875+
/// ```
876+
#[inline]
877+
#[unstable(feature = "option_get_or_default", issue = "82901")]
878+
pub fn get_or_default(&mut self) -> &mut T
879+
where
880+
T: Default,
881+
{
882+
self.get_or_insert_with(Default::default)
883+
}
884+
857885
/// Inserts `value` into the option if it is [`None`], then
858886
/// returns a mutable reference to the contained value.
859887
///

0 commit comments

Comments
 (0)