about summary refs log tree commit diff
diff options
context:
space:
mode:
authorCameron Steffen <cam.steffen94@gmail.com>2021-03-06 16:01:34 -0600
committerCameron Steffen <cam.steffen94@gmail.com>2021-03-08 09:24:10 -0600
commit7e3ebe76ee6b0b495112f56d16e7067a856c0cea (patch)
treeccde317be74a1743102a60795e94eb0be891fb27
parent1d6b0f626aad4ee9f2eaec4d5582f45620ccab80 (diff)
downloadrust-7e3ebe76ee6b0b495112f56d16e7067a856c0cea.tar.gz
rust-7e3ebe76ee6b0b495112f56d16e7067a856c0cea.zip
Add Option::get_or_default
-rw-r--r--library/core/src/option.rs28
1 files changed, 28 insertions, 0 deletions
diff --git a/library/core/src/option.rs b/library/core/src/option.rs
index e3c812a047c..9478e7f06bd 100644
--- a/library/core/src/option.rs
+++ b/library/core/src/option.rs
@@ -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.
     ///