Skip to content

Closures

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.

Create a closure that returns a function that increments a counter.

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())
}
Terminal window
1
2
3
1