<p>I was going through the Tour of Go when I noticed in the exercise where we're supposed to generate the fibonacci sequence with a lambda function I got two different results between this: </p>
<p>func fibonacci() func() int {<br/>
x := 0<br/>
y := 1<br/>
return func() int {<br/>
x, y = y, x+y<br/>
return x<br/>
}<br/>
} </p>
<p>and this:</p>
<p>func fibonacci() func() int {<br/>
x := 0<br/>
y := 1<br/>
return func() int {<br/>
x = y<br/>
y = x+y<br/>
return x<br/>
}<br/>
} </p>
<p>I thought both versions of the code would function the same but it didn't seem like the case.</p>
<hr/>**评论:**<br/><br/>gohacker: <pre><p>This is unrelated to closures. </p>
<blockquote>
<p>The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order. </p>
</blockquote>
<p><a href="https://golang.org/ref/spec#Assignments" rel="nofollow">https://golang.org/ref/spec#Assignments</a></p></pre>Tikiatua: <pre><p>Hi there, </p>
<p>The difference between the two versions is as follows:
In the version x,y = y, x+y both variables are assigned the value "at the same time". Therefore x will not have the value of y for the assignment y = x+y. In the second version, x is first assigned the value of y, then y is assigned the new value of x plus y.</p>
<p>Hope this clarifies things for you.</p></pre>tezeev: <pre><p>To make the point clear, statement like</p>
<pre><code>x, y = y, x + y
</code></pre>
<p>is equivalent to</p>
<pre><code>t := y
y = x + y
x = t
</code></pre></pre>
Difference between inline and separate line variable initializations in the context of closures?
blov · · 453 次点击这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传