Closures
A closure is a function value that references variables from outside its own body. makeMultiplier returns a new function each time it's called, and each returned function remembers its own factor, captured from the moment it was created.
main.go
Try it yourself →package main
import "fmt"
func makeMultiplier(factor int) func(int) int {
return func(n int) int {
return n * factor
}
}
func main() {
double := makeMultiplier(2)
triple := makeMultiplier(3)
fmt.Println(double(5))
fmt.Println(triple(5))
}Output
10 15
Closures can hold mutable state
A closure doesn't just read captured variables — it can also modify them, and that modification persists between calls. makeCounter's count variable lives on inside the returned closure, incrementing every time next() is called.
main.go
Try it yourself →package main
import "fmt"
func makeCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
next := makeCounter()
fmt.Println(next())
fmt.Println(next())
fmt.Println(next())
}Output
1 2 3
Next: goroutines — Go's lightweight, built-in concurrency primitive.
Practice exercise
Write a function makeAdder(x int) func(int) int that returns a closure adding x to its argument. Create addFive := makeAdder(5), then print addFive(10).