Question on for structure with no loop

agolangf · · 491 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Was looking through some examples from the google rpc library the other day and implemented a small rpc files server, I noticed this structure and wondered what was going on:</p> <pre><code> for { response, err := r.Recv() if err == io.EOF { break } if err != nil { log.Fatalf(&#34;could not greet: %v&#34;, err) } data := response.Image other := response.Type w.Header().Set(&#34;Content-Type&#34;, http.DetectContentType(other)) w.Write(data) } }) </code></pre> <p>This code works just as well without the for loop and the break however. </p> <p>Any insight on why I would do something like this?</p> <p>Edit: If you&#39;d like to take a look at the full code its available <a href="https://github.com/RobAWilkinson/go-file-server" rel="nofollow">here</a></p> <hr/>**评论:**<br/><br/>0xjnml: <pre><p><code>for {}</code> equals <code>for true {}</code>.</p></pre>sumobob2112: <pre><p>ah, so in this case, is it infinitely looping until it receives an EOF, or an err ?</p></pre>0xjnml: <pre><p>Correct.</p></pre>sumobob2112: <pre><p>awesome thanks for the tip. Read the docs but wasnt familiar with C for(;;){ } structure</p></pre>cakeFactory2: <pre><p>It&#39;s the Go equivalent of a while loop when there&#39;s no condition in the for</p></pre>j_d_q: <pre><p>It looks like it <em>does</em> loop. If there is no error it receives (<code>r.Recv()</code>) and writes it out. Then it would accept another and write it out until there are no more</p></pre>tgulacsi: <pre><p>The concrete example is for serializing streaming responses - if you remove the for cycle, onky the first response will be returned. Though if this endpoint is not streaming, you won&#39;t notice any difference.</p></pre>pstuart: <pre><p>seems kinda silly to set data and other rather than just use their direct sources.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

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