goroutine使用了外面的变量,造成闭包问题。怎么解决呢?

HUH函数
浏览 574回答 2
2回答

慕标琳琳

自己思考了一下。其实,既然是闭包。那么,只要将item作为参数,传递给这个循环goroutine,就可以了&nbsp;他作为形参,自然不会被修改// 从out队列接收数据&nbsp; &nbsp; &nbsp; &nbsp; for _,item := range result.Items {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("got item: ",item)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; go func(rec interface{}) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.ItemChan <- rec&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }(item)&nbsp; &nbsp; &nbsp; &nbsp; }带缓冲的channel,我认为不是一个好的办法。因为,缓冲终归会满。

一只斗牛犬

for _,item := range result.Items {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //fmt.Println("got item: ",item)//把这个放 go func()里面&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("got item: ",item)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.ItemChan <- item&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }()&nbsp; &nbsp; &nbsp; &nbsp; }这样你打印的就和接收到的数据是一样的了。因为go func 并不能保证立即执行,在它还没有执行的时候,item值已经被for循环改变了我有个疑问,你在写入的地方起goroutine是为了for循环不被写入阻塞吗?如果不想因为写入被阻塞,可以给channel定义一个缓冲。按照例子的,缓冲数定义为items的数量即可
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5