Closures
- Version
- 1.27
- Review
- Draft
Summary#
A function literal can read and change local variables from the function that creates it, even after that function returns. Each call to newAverage below creates a separate total and count for its returned function.
Syntax#
add := func(value int) {
total += value
}
Example#
package main
import "fmt"
func newAverage() func(float64) float64 {
var total float64
var count int
return func(value float64) float64 {
total += value
count++
return total / float64(count)
}
}
func main() {
scores := newAverage()
prices := newAverage() // separate total and count
fmt.Println(scores(10))
fmt.Println(scores(20))
fmt.Println(prices(4))
percent := 10
withTax := func(price int) int { return price + price*percent/100 }
fmt.Println(withTax(200))
percent = 20 // the closure sees the change
fmt.Println(withTax(200))
}
Expected output#
10
15
4
220
240
Common mistakes#
A closure captures the variable itself. To freeze a value, copy it into a new variable that does not change, or pass it as a parameter. Synchronize access when several goroutines share a captured variable and any of them writes to it.
Version applicability#
Closures work this way from Go 1.0. With a go directive of 1.22 or later, variables declared by a loop have a separate instance per iteration. Assigning to a variable declared outside the loop still shares it across iterations.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0