| > A closure is like an anonymous function. I like the article overall, but I have a bit of a pedantic note about this opening line. Using "like" suggests that there is some similarity that can be used to understand one thing from the other, but in truth these are two distinct (though related) technical terms, and I think phrasing this relationship as a simile may actually obstruct understanding rather than enable it. An anonymous function is just a function without a name. There's nothing particularly exciting about that, except that they only really make sense as a concept within the context of a language with first-class functions (i.e., a language where functions are values that can be passed around as arguments and such). A closure is a function paired with an environment. Technically (meaning "in the academic literature"), this can be any function at all --- named functions can be used to create closures. But in Rust this is not the case, since they only use the term in connection with anonymous functions. This is actually addressed in the first couple of lines of the Rust Book's entry on closures [1]. Saying "a closure is like an anonymous function" would be like me saying "a car is like a set of four wheels". While it is true that the four wheels are integral to the car's identity, it is not the case that these things are directly similar in the way that the word "like" suggests they are. [1] https://doc.rust-lang.org/book/ch13-01-closures.html |
Many programmers-in-training find it confusing as to why whether or not a function has a name seems to be tied to whether or not it has an environment (not that they phrase it that way but that's what it boils down to), and my usual answer is to explain something much like your post; the resolution is, there is no such connection. I have fielded this question in one form or another many times.
"Anonymous function" should not be used as a synonym for "closure". Generally I will follow along with the dominant language terminology if I am clearly in the context of a very particular language, but may include why I don't like the language community's terminology if it helps my point.