通道 returns 两次接收相同的值

Channel returns the same value twice on receive

您好,我有以下简单程序:
我有一个函数 printNums(nums chan int),它应该从一个通道中获取 3 个数字并同时打印它们。每次打印都在范围语句内的新 goroutine 中完成。
然而,当我 运行 这个程序时,我得到的不是预期的输出 4, 12, 32,而是 12, 12, 32。你能帮我找出问题出在哪里以及为什么我没有从通道收到已发送到通道的相同值吗?谢谢。

package main

import ("fmt")

func printNums(nums chan int){
    c := make(chan struct{}, 100)
        for num := range(nums){
            go func(){
                fmt.Println(num)
                c <- struct{}{}
            }()
        }
    <-c
    <-c
    <-c
}
func main(){
    nums := make(chan int)

  go func() {
      nums <- 4
      nums <- 12 
      nums <- 32 
      close(nums)
  }()

  printNums(nums)
}

您正在打印 num 的当前值,而不是创建 goroutine 时的值 num。循环变量每次都会被覆盖,goroutine 可能会看到更新后的值。

for num := range(nums){
    go func(x int){
         fmt.Println(x)
         c <- struct{}{}
    }(num)
 }