Make LazyCell<T, F> and LazyLock<T, F> covariant in both T and F - #159838
Make LazyCell<T, F> and LazyLock<T, F> covariant in both T and F #159838WaffleLapkin wants to merge 2 commits into
LazyCell<T, F> and LazyLock<T, F> covariant in both T and F #159838Conversation
LazyCell<T, F> and `LazyLock<T, F> covariant in both T and F LazyCell<T, F> and LazyLock<T, F> covariant in both T and F
5da2332 to
01615ea
Compare
|
This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed. Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers. |
| // | ||
| // **NOTE**: the important invariants here are that | ||
| // 1. `T` can only be written through `&LazyCell<T, F>` by being returned from `F` | ||
| // 2. `F` cannot be overwritten after `LazyCell` creation |
There was a problem hiding this comment.
This two assumptions are both fragile. We might want to provide an API in the future to clear a LazyCell similar to OnceCell, and we might want to provide an API to set the value directly without the callback. Making this type covariant in T will prohibit both.
I think the safe thing to do is to make it covariant in F but leave it invariant in T.
There was a problem hiding this comment.
What do you mean by "API [...] to clear a LazyCell similar to OnceCell"?
If you are talking about take, then it would not be a problem for these assumptions1. For LazyCell you would need something like fn take(&mut self, new_initializer: F) -> Result<T, F>. Notably since it would have to take &mut self, it does not interact with variance2.
Setting the value without callback would require LazyCell to be invariant in T. If we want to add such an API we should keep T invariant.
Footnotes
There was a problem hiding this comment.
Alright, maybe take() isn't a problem, but fn set(&self, value: T) -> Result<(), T> is.
See explanation for why it's valid that I wrote as a comment in
LazyCell:rust/library/core/src/cell/lazy.rs
Lines 55 to 91 in 5da2332
r? libs-api