From 7e3ebe76ee6b0b495112f56d16e7067a856c0cea Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Sat, 6 Mar 2021 16:01:34 -0600 Subject: [PATCH] Add Option::get_or_default --- library/core/src/option.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index e3c812a047c8c..9478e7f06bdf3 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -854,6 +854,34 @@ impl Option { // 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. ///