A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Closures

A closure is a function that references variables defined outside of its own scope:

  • The closure is created using an anonymous function defined within another function
  • The anonymous function can access and assign to variables from the parent function, even after the parent function has returned
  • The anonymous function is returned from the parent function
// A function that returns a closure.
func adder() func(int) int {
  sum := 0

  // Return an anonymous function.
  return func(x int) int {
    // Access a variable from the parent function's scope.
    sum += x
    return sum

// Assign the anonymous function to a variable.
f := adder()

f(1) // 1
f(1) // 2
f(1) // 3