-
Notifications
You must be signed in to change notification settings - Fork 109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How do I initialize a Lazy with a closure that captures a variable? (With fun recursion question) #156
Comments
Most of the time, if you want to store lazy in a field, it’s better to use once cell directly. See “config” example in the crate docs. Seems like we need to document on Lazy that sometimes you don’t need it…. |
I quite like the interface of I found this quite useful for reducing the amount I had to write. I don't know whether it makes sense to add something like this...
|
This issue seems to be related to #90. I tried to implement Lazy myself, but didn't solve the problem, because I ended up with an implementation very similar to once_cell's Lazy. In my opinion, this is a flaw in the Rust type system. |
edit: I just realized this usage of
|
I think there isn't much we can do here, so closing. That being said, it seems that this is a common an unfortunate footgun, so a PR to docs would be appreciated |
I think the support of "impl Trait" in variable in the language will solve this. |
1a) So I understand that I can do:
Because:
fn() -> String
fn() -> String
1b) I also understand that I can do:
Because:
fn() -> String
, since it captures something_
I can let the type system infer the type of the closure itself (closures are a Voldemort type, one cannot name their actual type in code so I couldn't replace_
with the true type even if I tried).2a) Now what if I wanted to put the Lazy into a struct?
Works fine
2b) But how would I do this in the case where my closure captures something?
_
doesn't work. Am I forced to do something like this?This isn't always convenient.
Start Edit A much simpler example than what I write below is something like
This doesn't compile because I want the two
Foo<F>
s to be the same type in order to put them in the vec, but they use different closures so they are not the same type.End Edit
For example, if Foo is recursive in any way (e.g. a lazy-tree, which is how I came across this):
There's no way I can add the function generic to
Foo
any more:struct Foo<F: FnOnce() -> Foo<F>>
. This is recursive, which is apparently fine on its own but it causes problems because onceF
is resolved it can only match a single closure. This means that all of theLazy
s all the way down need to use the same closure - which I obviously don't want.So, am I forced to use
Lazy<Foo, Box<dyn FnOnce() -> Foo>>
and box up all my closures? This is what I've got working but is there no nicer way?The text was updated successfully, but these errors were encountered: