(define (make-counter)
(let ((n 0)) (lambda () (set! n (+ n 1)) n)))
is guaranteed to work in any context where make-counter is called. Same in Go; though the syntax is a bit unwieldy due to having to specify types: func makeCounter() (func () int)) {
n := 0
return func () int { n++; return n }
}
Google's Go compiler is smart enough to allocate only the captured variable (n in this case) for such returned functions on the heap. There should be no failures.IIRC some algol-68 compiler did remove the restriction and allowed such full closures.