Middle
What is a closure in Go?
sobes.tech AI
Answer from AI
Closure in Go is a function that "remembers" values from its surrounding scope even after the outer function has finished. This allows capturing variables from outside and using them inside.
// Outer function
func makeCounter() func() int {
count := 0 // Variable to be captured
// Inner function (closure)
return func() int {
count++ // Capture and modify count
return count
}
}
// Usage example
func main() {
counter1 := makeCounter() // Create first closure
fmt.Println(counter1()) // Output: 1
fmt.Println(counter1()) // Output: 2
counter2 := makeCounter() // Create second closure (with its own count)
fmt.Println(counter2()) // Output: 1
}