Question about ranging over channels

blov · · 579 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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 &lt;-chan string) { for { select { case msg := &lt;-messenger: fmt.Println(msg) } } } </code></pre> <p>and this:</p> <pre><code>func readMessages(messenger &lt;-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 &#34;&#34; 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 &#34;the iteration values produced are the successive values sent on the channel until the channel is closed&#34; <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

579 次点击  
加入收藏 微博
1 回复  |  直到
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传