# Can someone explain closures to me

**URL:** <https://discourse.julialang.org/t/can-someone-explain-closures-to-me/105605>\
**Category:** Internals & Design\
**Tags:** performance, type-stability, closure\
**Created:** [October 31, 2023, 3:56am UTC](https://discourse.julialang.org/t/can-someone-explain-closures-to-me/105605 "2023-10-31T03:56:51Z")\
**Posts on this page:** 1\
**Showing post:** 14

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [November 2, 2023, 8:21pm UTC](https://discourse.julialang.org/t/can-someone-explain-closures-to-me/105605/14 "2023-11-02T20:21:41Z")

</div>

> [@greatpet](#):
>
> treating variables as bindings (that are never reassigned) is exactly what’s encouraged by a functional style

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](https://discourse.julialang.org/t/why-not-an-even-harder-scope/50087/22) 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.

> [@croberts](#):
>
> Do I want to add minimum 4 lines of code (3 for the struct, parameter, end) when I just want a one-off calculation?  
> …  
> Structs are a pain to use interactively: if I need to tweak my struct definition, I must either (A) restart my session (B) write a new struct with a new name (“my\_struct2”).

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”.

> [@croberts](#):
>
> What would be nice is something like an anonymous functor.

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.

---

_[View the full topic](https://discourse.julialang.org/t/can-someone-explain-closures-to-me/105605)._
