Closured variables and the go statement
In this section, we are going to talk about closured variables, which are variables inside closures, and the go
statement. Notice that closured variables in goroutines are evaluated when the goroutine actually runs and when the go
statement is executed in order to create a new goroutine. This means that closured variables are going to be replaced by their values when the Go scheduler decides to execute the relevant code. This is illustrated in the main()
function of goClosure.go
:
func main() {
for i := 0; i <= 20; i++ {
go func() {
fmt.Print(i, " ")
}()
}
time.Sleep(time.Second)
fmt.Println()
}
Running goClosure.go
produces the following output:
$ go run goClosure.go
3 7 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21 21
The program mostly prints the number 21, which is the last value of the variable of the for
loop, and not the other numbers. As i
is a closured...