Closures
Context
Section titled “Context”Go functions can be anonymous and can form closures. A closure is a function value that references variables from outside its body. It captures those variables and can use them even after the outer function has returned.
Example
Section titled “Example”Create a closure that returns a function that increments a counter.
Code example
Section titled “Code example”package main
import "fmt"
func counter() func() int { count := 0 return func() int { count++ return count }}
func main() { inc := counter() fmt.Println(inc()) fmt.Println(inc()) fmt.Println(inc())
another := counter() fmt.Println(another())}Output
Section titled “Output”1231