Closed a1phyr closed 2 years ago
Hm, I am a bit torn here -- it feels like From
is probably the best interface here. But that can't be const. On the other hand, const-creating a full OnceCell feels a bit odd. Do we have a real use-case for that? At the same time, the API does feel rather tidy.
:thinking: yeah, I guess, lets have this! The implementation looks good to me, but lets add a couple of tests to https://github.com/matklad/once_cell/blob/master/tests/it.rs to make sure the new API doesn't get broken by accident.
Actually, I didn't see the From
implementation when I wrote this patch, so I wrote with_value
for that, so I don't have a strong will to add this.
There might be a use-case for something like that, I guess (though very specific):
const fn get_some_value() -> Option<T> {
/* ... */
}
static CELL: OnceCell<T> = match get_some_value() {
Some(value) => OnceCell::with_value(value),
None => OnceCell::new(),
};
I think the main benefit of this would be discoverability, which is not great today, as shown by the linked issue (and my own experience ^^').
This PR adds
OnceCell::with_value
to bothsync::OnceCell
andunsync::OnceCell
. This enables creating an initializedOnceCell
at compile time and/or without synchronization cost.Additionally, this improve
Clone
implementations by removing a panicking branch, reducing synchronization cost and overridingclone_from
implementation.Closes #164