Sobes.tech
Middle

What is a closure in Go and how does it work?

sobes.tech AI

Answer from AI

A closure in Go is a function that "remembers" the values of variables from its surrounding lexical environment, even after that environment has ceased to exist.

The working principle is as follows:

  1. When a closure is created (for example, inside another function), it captures references to variables from the scope where it was declared.
  2. These captured variables live as long as the closure itself, even if the function in which they were declared has already finished.
  3. Each time the closure is called, it can access and modify these captured variables.

Example:

package main

import "fmt"

func makeCounter() func() int {
	count := 0 // Variable from the outer environment
	return func() int { // This is a closure
		count++ // It accesses and modifies `count`
		return count
	}
}

func main() {
	counter1 := makeCounter()
	fmt.Println(counter1()) // Outputs 1
	fmt.Println(counter1()) // Outputs 2

	counter2 := makeCounter() // Creates a new closure with its own `count`
	fmt.Println(counter2()) // Outputs 1
}

In this example, the makeCounter function returns a function (a closure). This closure "captures" the variable count. Each call to the returned function increases the value of count belonging to that specific closure instance.