Hacker News new | ask | show | jobs
by electroly 1119 days ago
Closing over variables is the thing that makes it a closure. Otherwise, you just have an anonymous function. A closure is a function plus the captured environment.

The difference is meaningful here. You have to allocate a closure (and deal with its lifetime and the lifetimes of the variables it references) but the anonymous function is just a pointer to static code in the binary. That's the entire difficulty with closures in non-GC languages.

This distinction matters less in GC languages where you're not thinking about lifetimes either way.

2 comments

As per Rust reference, even a capture-less closure is a closure and distinct from an anonymous functions.

Also, your arguments only partly apply in Rust. Rust doesn't heap-allocate closures. And you also often don't have to deal with lifetimes - a closure that captures variables by move or copy is perfectly self-contained

The difference between a closure that captures and a closure that doesn't is like the difference between `(T)` and `()` - same kind of thing, so it adheres to the same terms and behaviors

> You have to allocate a closure

That's incorrect, a closure in Rust compiles down to a static function that takes its environment as an argument. None of that requires a heap allocation in the above code.

Stack allocation is still allocation.
Literally no considers that to be the case? Like I have never met anyone who would consider declaring an integer variable "allocation"
Write a compiler sometime; it'll be more obvious why the term of art is "stack allocation" instead of something that doesn't include the word "allocation." You'll understand why C's "alloca" function and C#'s "stackalloc" keyword are named like that. Stack overflows will make more sense--obviously you can't allocate forever, because you are indeed allocating memory.

As a parting gift, I'll give you one guess what the title of the Wikipedia article on thread stacks is.

https://en.wikipedia.org/wiki/Stack-based_memory_allocation

I didn't suggest a heap allocation; indeed, in C++ too you can have stack allocated closures. I mean that it's not simply a pointer to static code; there is an associated data structure.