by roblabla · 4y ago · 0 comments
e.g. in C++, where one has to make capture by reference explicit
int i = 0;
auto f = [x = i, &y = i] { //x captures i by value, y by reference
std::cout << "Value:" << x << ", Reference:" << y;
};
i++;
f();
will print out "Value: 0, Reference: 1".>at least a differently scoped variable of the same name referring to the same value, but that's not lexical scoping anymore
not lexical scoping? That's literally just how closures work under the hood.
And that's exactly why closures have to deal with references (or copies) - every implementation of them is a function pointer and a record for the lexical environment, the latter of which requires that at closure creation time the relevant bindings are captured, either by creating a reference or making a copy.
I also don't understand why C++'s (or Rust's) closures would be 'fake'. If you capture by reference, they work exactly like the closures of other languages. Not having a GC just means you have to be wary of lifetimes. If you use a reference counting pointer (/some other GC'd pointer) you literally have the same closures as other languages.
>>> funcs = []
>>> for i in range(10):
... def f():
... print(i)
... funcs.append(f)
...
>>> [f() for f in funcs]
9
9
9
9
9
9
9
9
9
9
[None, None, None, None, None, None, None, None, None, None]C++ lambdas do the same thing if you pass a pointer.
Python would do the same thing if you had a mutable non-threadsafe objects passed to threads. Eg if you iterate over a list of dicts, and modify the dicts, you'll get the same effect.
So then the question becomes, why does v get re-used, instead of assigning a new pointer each time? Dunno, probably performance. I could see the latter generating a lot of garbage, which can be totally avoided if you don't pass mutable references to goroutines.
What go really lacks IMHO is some kind of const modifier for these kind of references. Maybe it does, all I remember are const scalars.
You'll have the same problem with a simple integer (for example, as in https://go.dev/play/p/uqvRoO3ynZt). Nothing to do with v being a reference to something.