package main
import "fmt"
// The function createCounter returns anonymous function defined within its body.
// The returned function encapsulates the variable count, creating a closure.
func createCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
// We invoke createCounter, storing the result (a function) in counter variable.
// This function captures and retains its own count value,
// which updates with each subsequent invocation of createCounter.
counter := createCounter()
fmt.Println(counter())
fmt.Println(counter())
fmt.Println(counter())
newCounter := createCounter()
fmt.Println(newCounter())
}
// $ go run main.go
// 1
// 2
// 3
// 1
A simple example of using closures in Go.