背景
go1.22版本 for loop每輪循環都生成新的變量.
原諒: https://tip.golang.org/doc/go1.22
Previously, the variables declared by a “for” loop were created once and updated by each iteration. In Go 1.22, each iteration of the loop creates new variables, to avoid accidental sharing bugs. The transition support tooling described in the proposal continues to work in the same way it did in Go 1.21.
測試
接下來將使用同樣的代碼, 分別使用go1.21.4和go1.22.4版本來運行:
package mainimport ("fmt""time"
)func main() {for i := 0; i < 5; i++ {go func() {fmt.Println(i, &i)}()}time.Sleep(time.Second)
}
在我的mac 機器上, go1.21.4的運行結果(可能每次都不太一樣):
$ go run main.go
5 0x14000112008
5 0x14000112008
5 0x14000112008
3 0x14000112008
5 0x14000112008
使用go1.22.4運行的結果:
$ go run main.go
0 0x14000110018
4 0x14000110038
3 0x14000110030
1 0x14000110020
2 0x14000110028
總結
go1.22版本對于for循環中的每個循環變量, 每輪循環都是都是使用新的變量.