<p>Hey guys, I'm going through <a href="https://tour.golang.org/concurrency/5" rel="nofollow">this exercise</a> in a <strong>A Tour of Go</strong>. Can someone explain to me what is the purpose of the <strong>return</strong> statement in this snippet?</p>
<pre><code>func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}
</code></pre>
<p>What is it returning? The fibonacci function doesn't even specify a a return type (I thought you had to specify a return type if you're going to return something). Can someone please help me understand why that isn't just a random return statement?</p>
<p>Thanks</p>
<hr/>**评论:**<br/><br/>dlsniper: <pre><p>It's used to terminate the for loop so that the function can exit.</p></pre>paradoxops: <pre><p>Aaah thank you sir </p></pre>iwsbfgl: <pre><p>I would amend that to it returns from the function to escape the loop. The difference is that if there was some final statement after the loop but before the end of the function, it would not be executed. </p></pre>jeremiahs_bullfrog: <pre><p>And <code>break</code> would only break out of the select. You could break out of the loop with a label in this case since there are no statements after.</p></pre>iwsbfgl: <pre><p>In this case, that would be over complicating things. But I am generally against labels and breaks to labels. There usually is a less clever way. </p></pre>itsmontoya: <pre><p>If there are no return variables, return will just end a func early</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传