Function closures

Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.

For example, the adder function returns a closure. Each closure is bound to its own sum variable.

function-closures.go

  1. package main
  2. import "fmt"
  3. func adder() func(int) int {
  4. sum := 0
  5. return func(x int) int {
  6. sum += x
  7. return sum
  8. }
  9. }
  10. func main() {
  11. pos, neg := adder(), adder()
  12. for i := 0; i < 10; i++ {
  13. fmt.Println(
  14. pos(i),
  15. neg(-2*i),
  16. )
  17. }
  18. }