Can someone explain why does this work?

blov · · 479 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<pre><code>package main import &#34;fmt&#34; func main() { var a [4]int a[0] = 1 a[1] = 2 a[2] = 3 a[3] = 4 fmt.Println(a) //Inplace swap - how come this works? a[0], a[1] = a[1],a[0] fmt.Println(a) } </code></pre> <p><a href="https://play.golang.org/p/awDpqht3NX">https://play.golang.org/p/awDpqht3NX</a></p> <p>Shouldn&#39;t a[0]=2 and a[1]=2 ?</p> <hr/>**评论:**<br/><br/>hanmunjae: <pre><p>The RHS is evaluated before any assignments are done. <a href="https://golang.org/ref/spec#Assignments">https://golang.org/ref/spec#Assignments</a></p></pre>weberc2: <pre><p>By &#34;evaluated&#34;, you mean something like a temp variable is created to store off the evaluation of the array indexing?</p></pre>hanmunjae: <pre><p>You can think of it like that, yes. Not just array indexing, but the value of every expression on the right hand side of the &#34;=&#34;.</p></pre>weberc2: <pre><p>Yeah, thanks for confirming. I tried the following experiment to test if it was a facet of array indexing or any expression:</p> <pre><code>a := 0 b := 1 a, b = b, a </code></pre></pre>9nut: <pre><p>it&#39;s in the language spec: <a href="https://www.google.com/?gws_rd=ssl#q=site:golang.org+%22The+assignment+proceeds+in+two+phases.%22">https://www.google.com/?gws_rd=ssl#q=site:golang.org+%22The+assignment+proceeds+in+two+phases.%22</a></p></pre>avsej: <pre><p>what if equals is a function? in this case it would be natural to put copies of the arguments to the stack and call the function</p> <p><a href="https://play.golang.org/p/9eJJmvmot5" rel="nofollow">https://play.golang.org/p/9eJJmvmot5</a></p></pre>kpmy: <pre><p>Objects (one object, whatever) on the left and values of objects on the right. First you take (calculate) values, then do the assignment. </p></pre>

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

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