Go by Example: Closures
Understand Closures in Go, anonymous functions that can capture and maintain state from their surrounding scope. This example demonstrates how to create closures, how they isolate data, and their utility in functional programming patterns.
Code
package main
import "fmt"
// intSeq returns a function that yields the next int
func intSeq() func() int {
i := 0
return func() int {
i++
return i
}
}
func main() {
// Create a new generator
nextInt := intSeq()
// Call it a few times
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
// Create another generator, separate state
newInts := intSeq()
fmt.Println(newInts())
}Explanation
Go supports anonymous functions, which can form 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.
Closures are powerful because they "capture" variables from their surrounding scope, maintaining the state of those variables even after the outer function has returned. This allows for data isolation and stateful functions without using global variables or structs.
Key concepts of closures:
- Variable Capturing: Inner functions retain access to variables defined in their outer scope.
- State Persistence: Captured variables survive as long as the closure exists.
- Data Isolation: Each closure instance has its own independent state.
- Use Cases: Generators, middleware, event handlers, and functional options.

