4 ms·
If you hide pointers and destructively update variables, this happens easily. I'd say the Go problem is a bit worse because there are also exposed pointers via
by beeforpork 4y ago
If you hide pointers and destructively update variables, this happens easily. I'd say the Go problem is a bit worse because there are also exposed pointers via that '&' operator.
But the problem should have been known when the language was designed. In CommonLisp, i.e., quite a mighty but old language, it is the same: the capture is on a loop variable that is destructively updated:
(setf refs (loop for i in '(1 2 3) collect #'(lambda () i)))
-> (#<function) #<function> #<function>)
(mapcar #'(lambda (f) (funcall f)) refs)
-> (3 3 3)
The same done with a fresh function parameter works. And since this is the usual style in Lisp, I suppose the problem will not be that obvious like in Go:
(setf refs (mapcar #'(lambda (i) #'(lambda () i)) '(1 2 3)))
-> (#<function> #<function> #<function>)
(mapcar #'(lambda (f) (funcall f)) refs)
-> (1 2 3)