RainbowMango / GoExpertProgramming

《Go专家编程》Go语言快速入门,轻松进阶!
1.85k stars 306 forks source link

[疑问]第二章for range #109

Open txbxxx opened 5 hours ago

txbxxx commented 5 hours ago

问题描述

func main() {
    s := []int{1,2,3}
    var wg sync.WaitGroup
    wg.Add(len(s))
    for _,v := range s {
        go func ()  {
            fmt.Println(v)
            wg.Done()
        }()
    }
    wg.Wait()
}

如何找到这个错误

您认为应该如何?

这里应该是随机输出1 2 3 的顺序而不是3个3吧

图片 如果有可能,尽量提供图片。

其他补充信息

RainbowMango commented 3 hours ago

你说得对。我猜你用的Go版本应该是 v1.22+。 在v1.21及之前的版本中,大概率是输出3个3。在v1.22中官方优化了这个问题。for 循环中的变量将不会共享。

详见Release Notes: https://go.dev/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.