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

Why doesn't Lazy::new() take FnOnce? #6

Closed Boscop closed 5 years ago

Boscop commented 5 years ago

Why doesn't Lazy::new() take FnOnce? Is it because it would require Box<FnOnce>? But that's possible on stable: https://crates.io/crates/boxfnonce

Btw, when to use unsync's OnceCell vs Lazy? And what's their advantage over Option::get_or_insert_with?

I'm looking for a replacement for Option::get_or_insert_with that would be like Lazy::new() but taking a FnOnce. It's important so that I can propagate the FnOnce requirement up, in my code that has multiple "deref" locations (but one init location). OnceCell::get_or_init() or Option::get_or_insert_with would have to be used at every "deref" location but then the compiler complains if I pass it a FnOnce. But I want to only require callers to give me a FnOnce. So it would all work well if Lazy::new() would take a FnOnce..

matklad commented 5 years ago

Why doesn't Lazy::new() take FnOnce?

That is possible, but not directly on top of OnceCell. I think something like SwapCell will be required here.

Btw, when to use unsync's OnceCell vs Lazy?

explained in https://docs.rs/once_cell/0.1.6/once_cell/#general-purpose-lazy-evaluation

And what's their advantage over Option::get_or_insert_with?

Option requires &mut, OnceCell needs only &