Ephemeral (or "weak") closures

I couldn't rest and had to think about this again :weary:…

This led me to consider trying something more easy:

  • store all closures directly in the scope handle
  • move a (wide) pointer to the extended closure to allow calling the original closure from there (while keeping the dropping managed entirely by the scope handle)
  • Use an Arc<RwLock<bool>> to syncronize execution of closure and dropping of scope

Here is my code (Playground) including comments and my original tests.

With my new approach, the string will be printed before it's dropped: (Playground)

Output:

Hello World
DROPPED


Amendment: It's possible to be generic over a (single) argument and return value by using an extra indirection. See modified example here (Playground), where the closures can retrieve an argument and return a value (requires double-boxing in line 57 though).

(Assuming the whole thing is safe now… :sweat_smile:)

1 Like