Closed tisonkun closed 5 months ago
This proposal is straightforward so the problem is the motivation I want to add new APIs.
even if straightforward, we need an example of “this is what the workaround looks like now” and “this is how the same thing would look with this proposal”. This can just be a simplified version of your linked comment.
And we want to see code, not links, in the solution sketch.
@tgross35 Updated.
cc @tgross35 @dtolnay anything blocks here or how can I get some feedback to move forward?
Thank you! This looks great to me.
These methods are the equivalent of the lazycell
crate's borrow_mut_with
and try_borrow_mut_with
, which are used by Cargo, blocking https://github.com/rust-lang/cargo/issues/9310. So I am eager for this to be supported better by OnceCell
.
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 https://github.com/rust-lang/rust/issues/109737The problem I encountered at https://github.com/rust-lang/rust/issues/74465#issuecomment-1668766041 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 https://github.com/rust-lang/rust/pull/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
What 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: