It’s interesting to note that if bindings are not reassigned, it’s the same effect as and implemented as if the instance were captured. But you can’t always capture instances because closures like do
blocks and comprehensions are expected to reassign local variables like any other local scopes; for example, a foreach
-do
block should do the same thing as a for
-loop. Here’s a link to the middle of a thread for a few comments addressing this. Note that as explained prior, the examples’ reassigned variables are Core.Box
ed, and the lack of type declarations means retrieving the variable propagates type instability. Annotating the variable, even generically like t::T = 0
, isolates the type instability to the Core.Box
, though there’s nothing that can be done about the extra heap allocation because a variable that outlives its scope cannot be stored in a stack.
Right, closures handle their underlying functors for you so you don’t have to edit multiple places in code, hence “often a lot more convenient to write”.
That wouldn’t work, an unnamed composite cannot distinguish 2 separate closures that capture the same variables. Closures do make names for the underlying structs, kind of gensym
ed but not sure how.