Add get_mut_or_init and get_mut_or_try_init for OnceCell #294
Labels
ACP-accepted
API Change Proposal is accepted (seconded with no objections)
api-change-proposal
A proposal to add or alter unstable APIs in the standard libraries
T-libs-api
Proposal
Problem statement
OnceCell
has been a stable API since 1.70.0 with the following methods:pub fn get(&self) -> Option<&T>
- stale since 1.70.0;pub fn get_mut(&mut self) -> Option<&mut T>
- stable since 1.70.0;pub fn set(&self, value: T) -> Result<(), T>
- stable since 1.70.0;pub fn get_or_init<F>(&self, f: F) -> &T
- stable since 1.70.0;pub fn get_or_try_init<F, E>(&self, f: F) -> Result<&T, E>
- unstable Tracking Issue foronce_cell_try
rust#109737The problem I encountered at rust-lang/rust#74465 (comment) is that I need to obtain a
mut
of OnceCell likeget_mut
reference and am unsure if it's initialized. So, aget_mut_or_init
orget_mut_or_try_init
counterpart to the ones withoutmut
is needed.Motivating examples or use cases
This proposal is straightforward so the problem is the motivation I want to add new APIs.
Current workaround:
Expected code with
get_mut_or_init
:Solution sketch
Add these two methods. It should be intuitive and I try it in rust-lang/rust#114788. Since it's an API change, I was guided to create this ACP.
It looks like:
Alternatives
Not yet. The solution proposed above should be the simplest one.
Links and related work
once_cell
rust#74465once_cell_try
rust#109737What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
Second, if there's a concrete solution:
The text was updated successfully, but these errors were encountered: