<p>I am new to go, and I am trying to understand how goroutines work. I don't understand the following code. It only prints '10'. I thought go was pass by value? What exactly is going on with defer and wait in this case?</p>
<p>Also what is the difference in the order in which defer is called? Does it not make a difference? Are the following the same?</p>
<pre><code> defer wg.Done()
fmt.Println(i)
fmt.Println(i)
defer wg.Done()
</code></pre>
<p><a href="https://play.golang.org/p/T0_Q8HHF0E" rel="nofollow">https://play.golang.org/p/T0_Q8HHF0E</a></p>
<hr/>**评论:**<br/><br/>Logiraptorr: <pre><p>Go is pass by value, this issue with the code you linked is that the value here is the address of i. For loops in Go reuse the same memory for each loop iteration, so all go routines created in the loop are referring to the same address. When they all execute (after the loop has finished), i is 10. See <a href="https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables" rel="nofollow">here</a> for more information.</p></pre>phat4life: <pre><p>awesome thanks</p></pre>antonmry: <pre><p>you may try something like <a href="https://play.golang.org/p/oZn2Oy_jMq" rel="nofollow">https://play.golang.org/p/oZn2Oy_jMq</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传