matklad / once_cell

Rust library for single assignment cells and lazy statics without macros
Apache License 2.0
1.84k stars 110 forks source link

Return value from `set` #148

Closed daxpedda closed 3 years ago

daxpedda commented 3 years ago

This adds a function called set_and_get that returns the value on setting it. Originally I wanted to implement it only for sync, because the value was just being discarded, see the comment I added to unsync::OnceCell::set_and_get.

Is there interest in a feature like this?

EDIT: My use case is to initialize but return an Err if it already is initialized. This can be done by calling OnceCell::set and then OnceCell::get, this offers an optimization, that culls this to only one function call. This can't be solved by using OnceCell::get_or_init because it doesn't offer any indication if it was already set.

matklad commented 3 years ago

I am torn on this one. One the one hand, set not returning a reference to a value is definitelly a loss of generality. On the other hand, the fully general signature here would be -> Result<&T, (&T, T)>. On the third hand, it feels like .set, .get and .get_or_init give the necessary tools to express this without adding extra methods.

Anothe option would be to add a simpler fn insert(&self, value: T) -> &T methond, a-la Option<Insert>.

daxpedda commented 3 years ago

On the other hand, the fully general signature here would be -> Result<&T, (&T, T)>.

I don't mind implementing it like this if you want.

On the third hand, it feels like .set, .get and .get_or_init give the necessary tools to express this without adding extra methods.

So the only reason .get_or_init doesn't cover this for me is because it doesn't tell me if it was already initialized. I want an error if it's already initialized. So I'm kinda forced to use .set and .get to achieve this.

Anothe option would be to add a simpler fn insert(&self, value: T) -> &T methond, a-la Option<Insert>.

Same as above, it doesn't solve my use-case.

Sorry, I think I should have explained my use-case more clearly in the OP.

daxpedda commented 3 years ago

I explained my use-case in OP more clearly now.

matklad commented 3 years ago

should be covered by #151