Skip to content

Commit 1c3fea2

Browse files
authored
Rollup merge of #82849 - camsteffen:option-get-or-default, r=joshtriplett
Add Option::get_or_default Tracking issue: #82901 The original issue is #55042, which was closed, but for an invalid reason (see discussion there). Opening this to reconsider (I hope that's okay). It seems like the only gap for `Option` being "entry-like". I ran into a need for this method where I had a `Vec<Option<MyData>>` and wanted to do `vec[n].get_or_default().my_data_method()`. Using an `Option` as an inner component of a data structure is probably where the need for this will normally arise.
2 parents 48a393e + 1cc8c4d commit 1c3fea2

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

compiler/rustc_mir/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ Rust MIR: a lowered representation of Rust.
2525
#![feature(stmt_expr_attributes)]
2626
#![feature(trait_alias)]
2727
#![feature(option_expect_none)]
28+
#![feature(option_get_or_default)]
2829
#![feature(or_patterns)]
2930
#![feature(once_cell)]
3031
#![feature(control_flow_enum)]

compiler/rustc_mir/src/transform/coverage/graph.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -392,10 +392,7 @@ impl BasicCoverageBlockData {
392392
}
393393
}
394394
let operand = counter_kind.as_operand_id();
395-
if let Some(replaced) = self
396-
.edge_from_bcbs
397-
.get_or_insert_with(FxHashMap::default)
398-
.insert(from_bcb, counter_kind)
395+
if let Some(replaced) = self.edge_from_bcbs.get_or_default().insert(from_bcb, counter_kind)
399396
{
400397
Error::from_string(format!(
401398
"attempt to set an edge counter more than once; from_bcb: \

library/core/src/option.rs

+28
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)