dongyaobo9081 2019-09-10 02:46
浏览 63

为什么在我的代码中goroutine似乎自动冻结了循环变量

import (
    "fmt"
)


func Print(i int) {
    fmt.Println(i)
}

func PrintR(i *int) {
    fmt.Println(*i)
}


func main() {
    for i := 0; i < 10; i++ {
        go Print(i)   // Get: 1 9 2 3 4 5 7 6 8 0

        //go func() {
        //  Print(i)
        //}()  // Get: 10 10 7 10 4 10 7 10 10 10 10

        //go PrintR(&i)  // Get: 7 10 10 7 10 7 10 10 10 10
    }
    select {

    }
}

The 2nd, 3rd example got the expected output, but I have thought that the 1st case's output go Print(i) should be similar to the 2nd's since both of them do not use a new variable to freeze the current value of i. What cause the difference?

  • 写回答

2条回答 默认 最新

  • duanla3319 2019-09-10 02:57
    关注

    Go passes parameter by value. Your first example does actually create a new variable and copy the current index into it before launching the new goroutine, which is the same as your 3rd example.

    评论

报告相同问题?

悬赏问题

  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)