I come from Python and JavaScript, so I'm not used to making this distinction between functions and closures.
I mean, a top-level function also have access to top-level values such as constants, no? So that feels like their environment to me, but there is probably some subtle difference that I miss?
Indeed! This makes me see closures as the more primitive building block from which you can create functions (by assigning a name to your closure). However, I guess this is much easier in a garbage collected language like Python, JavaScript or Go?
On the other, Rust does allow me to return a closure, just like Go does:
Can I tell the difference between a closure and a "real" function in my code? That is, can there be a behavioral difference between code which uses a closure
let mut pos = adder();
// call pos(i) several times.
and code which uses a function:
fn pos(i: i32) -> i32 {
// ...
}
// call pos(i) several times
I guess the pos
function must keep state in a mutable global variable, and I guess this implies that I should be able to change this variable from outside of pos
. In the closure case, the state is completely internal to the closure and I have no way of getting access to it. So that might be one difference?