<p>Hey all! I am writing a function that will read messages sent to a channel and used like this:</p>
<pre><code>go readMessages(messenger)
</code></pre>
<p>Where <code>messenger</code> is the channel of string messages.</p>
<p>I am confused about the difference between this:</p>
<pre><code>func readMessages(messenger <-chan string) {
for {
select {
case msg := <-messenger:
fmt.Println(msg)
}
}
}
</code></pre>
<p>and this:</p>
<pre><code>func readMessages(messenger <-chan string) {
for msg := range messenger {
fmt.Println(msg)
}
}
</code></pre>
<p>Are they equivalent? Or Should I prefer one over the other and why?</p>
<hr/>**评论:**<br/><br/>lausan: <pre><p>you should use the range option. the first example will continue to print "" after the channel is closed on every iteration of the loop due to the <a href="https://golang.org/ref/spec#Close" rel="nofollow">behavior of closed channels</a>. the range option works as expected since "the iteration values produced are the successive values sent on the channel until the channel is closed" <a href="https://golang.org/ref/spec#RangeClause" rel="nofollow">from the range clause spec</a>.</p></pre>nesigma: <pre><p>Thanks for the explanation. I ended up using the select version since I later discovered that I have to make the goroutine end at some point by listening for a done/quit channel and that cannot be done with the for range version.</p></pre>Kraigius: <pre><p>From my limited experience, the infinite loop for + select is useful if you are reading from multiple channels. You will also have to add the logic needed to break away from that loop.</p>
<p>If you are reading from a single channel, the range is pretty solid. It will iterate until the channel is closed and empty.</p></pre>binaryblade: <pre><p>Use the range, it behaves better when the channel closes.</p></pre>georgetso: <pre><p><a href="https://gist.github.com/georgetso/517de63494ae83a5cecbf25909a7bd48" rel="nofollow">try this</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传