最近发了go1.21.0, 听说循环中的变量有变化,跑一下看看。
1.21.0默认还是和之前一样的。通过设置 go env -w GOEXPERIMENT=loopvar
让新语义生效
package main
import (
"fmt"
"sync/atomic"
"time"
)
func main() {
var is []int32
for i := int32(0); i < 10; i++ {
is = append(is, i)
}
var kk atomic.Int32
c := int32(0)
for _, i2 := range is {
c += i2
go func() {
time.Sleep(time.Millisecond * 50)
kk.Add(i2) // goland提醒:Loop variables captured by 'func' literals in 'go' statements might have unexpected values
}()
}
// 就不用WaitGroup了
time.Sleep(time.Second * 3)
fmt.Println(kk.Load(), c) // 不启用GOEXPERIMENT=loopvar打印90,45 ,否则打印45,45
}
标签:int32,变量,go1.21,45,循环,func,time,go
From: https://www.cnblogs.com/xiaotushaoxia/p/17623103.html