Closures
Functions that capture variables from their surrounding scope, including closures used by goroutines.
A closure is a function that keeps access to a variable from the surrounding code where it was created. It can still use that variable after the surrounding function returns.
Each call to makeCounter returns a function with its own saved count value:
package main
import "fmt"
func makeCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
counter := makeCounter()
fmt.Println(counter(), counter()) // 1 2
}A goroutine is a function call started with go that can run while its caller continues. Passing the loop value as an argument gives each call its own copy. A wait group is a counter that lets main wait for these calls to finish. defer schedules Done to run when that function returns. All three values print, but their order may vary:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
fmt.Println(n)
}(i)
}
wg.Wait()
}In production
The Go version in go.mod affects loop variables. Go 1.22 and later create a new loop variable each time; older versions reuse one variable. Passing the value as an argument makes this example work with either version.