#Self referencing closure

4 messages · Page 1 of 1 (latest)

acoustic eagle
#

My goal is to let the user add a closure to a struct that accepts the struct as an input, as a way to add a sort of custom method.
Its purpose is to update the struct before that struct handles certain events. I plan to add a second one to run after events as well.

Here is a minimal example of the issue I have:
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=f8119ccf560548ed681f39ece0e07711

And the error I get:

error[E0644]: closure/coroutine type that references itself
 --> src/main.rs:8:15
  |
8 |         func: |_| {}
  |               ^^^ cyclic type of infinite size
  |
  = note: closures cannot capture themselves or take themselves as argument;

Shouldn't this not be of infinite size since I took in the struct containing the closure by reference?
Is my only option to box it up and use dynamic dispatch?

austere imp
#

per the linked issue info, you can't have a closure type depend on itself

#

but also note that your function will be impossible to call, anyway

#

calling func means borrowing it, and since you have borrowed self.func, you won't be able to borrow all of self to create &mut MyStruct<F> to pass it to func