Often I have code where Option is used to indicate whether a value has been initialized or not. In these instances I often have code that either wants to use the value directly or initialize it and then use the value. So what I'm looking for is similar to as_ref()/as_mut() except they should return &T/&mut T respectively, and take either a value or a closure.
I think I would call the functions get{,_mut}_or_insert{,_with}() marrying the get_ functions (for example in hashmaps) for getting references with the or_insert Entry like functions.
Isn't this just as_ref/mut().unwrap_or(val) and as_ref/mut().unwrap_or_else(|| val) ?
Edit: These don't modify the original Option which I guess it what you wanted
indeed
See also #25149 and #29203. Also, this seems fixed by #39289.
AIUI, this is not fixed by #39289, because this issue is referenced as the tracking issue for the implementation and should stay open until it's decided whether this is to be stabilized or backed out.
Ah, right. Maybe you could put "Tracking issue" in the title.
As this issue is quite old already (over 3 months), would it be possible to stabilize these two functions soon?
@rfcbot merge
@rfcbot fcp merge
Team member @brson has proposed to merge this. The next step is review by the rest of the tagged teams:
No concerns currently listed.
Once these reviewers reach consensus, this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!
See this document for info about what commands tagged team members can give me.
To be clear, the APIs proposed here for stabilization are:
impl<T> Option<T> {
fn get_or_insert(&mut self, v: T) -> &mut T;
fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T;
}
:bell: This is now entering its final comment period, as per the review above. :bell:
The final comment period is now complete.
This isn't Entry-like. If it was, it would be possible to do the following:
match opt_value.entry() {
VacantEntry(entry) => entry.insert(x),
OccupiedEntry(entry) => { assert_eq!(entry.get(), x); }
}
@dhardy That particular example can be written as:
```rust
match opt_value {
ref mut entry @ None => *entry = Some(x),
Some(ref entry) => assert_eq!(entry, x),
}
To save time for people researching this, the feature landed in stable at Rust 1.20 (source: 64c1b23).
@raphlinus I think that commit is wrong :-) The function in question doesn't show up in the 1.20.0 docs but does in the 1.21.0 docs. Nope, never mind; I just forgot how to search, sigh.
GitHub does say that commit is only in the 1.21.0 tag though...
Ah, the 1.20.0 commit was a backport, thus why it's a different tag.
Most helpful comment
To be clear, the APIs proposed here for stabilization are: