<p>Hey everyone,</p>
<p>I'm new to Golang. I'm doing <a href="https://tour.golang.org/flowcontrol/7" rel="nofollow">this exercise</a> in
<strong>A Tour of Go</strong> and cannot figure out why the output is what it is.</p>
<p>Here is the code:</p>
<p>package main</p>
<pre><code>import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
// can't use v here, though
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
}
</code></pre>
<p>Here is the output:</p>
<pre><code>27 >= 20
9 20
</code></pre>
<p>Okay, so the program is calling pow(3, 2, 10) first. This will result in <strong>9</strong>.
Then, the program calls pow(3, 3, 20). This will result in <strong>27 >= 20</strong></p>
<p>According to my understanding, the output should be:</p>
<pre><code>9
27 >=20
</code></pre>
<p>What am I missing here? The tutorial makes a special note that <strong>(Both calls to pow are executed and return before the call to fmt.Println in main begins.)</strong>, but I guess I don't quite get what it's saying. Can someone elaborate on the steps going on here?</p>
<hr/>**评论:**<br/><br/>ajd007: <pre><p>Essentially, the order of execution here is:</p>
<ol>
<li><p>First 'pow' call</p></li>
<li><p>Second 'pow' call</p></li>
<li><p>fmt.Println using results of first two</p></li>
</ol>
<p>The Println in 'main' doesn't evaluate until both of it's arguments have been evaluated. Thus, the results of the pow calls won't be printed until the very end.</p>
<p>So:</p>
<ol>
<li><p>pow(3, 2, 10) is evaluated. Nothing is printed to screen, function returns 9</p></li>
<li><p>pow(3, 3, 20) is evaluated. '27 >= 20' is printed to screen, function returns 20.</p></li>
<li><p>Now that both arguments have been evaluated, fmt.Println(9, 20) is evaluated, '9 20' is printed to screen.</p></li>
</ol>
<p>Ninja edit:
I just realized that your confusion may stem from the difference between printing text to screen and the return value of the function. The first call to pow returns a value (but doesn't print anything to the screen) to the caller, main. The second call to pow prints a line to screen and also returns a value to main. Then main goes and prints the return values of both calls to screen.</p></pre>hanmunjae: <pre><p>pow(3, 2, 10) and pow(3, 3, 20) are arguments to fmt.Println. They will both finish running before the Println in main() prints anything. That's why "27 >= 20" prints first.</p>
<p>After both functions return, fmt.Println "9 20", which are the return values of pow(3, 2, 10) and pow(3, 3, 20), respectively. pow() always returns a value, whether or not it prints something.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传