Help me understand this example from the tour

xuanbao · · 346 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>So I want to refresh my knowledge of Go (I haven&#39;t programmed in it in a while), and I&#39;m taking the tour of Go, and I came across this example <a href="https://tour.golang.org/moretypes/25">https://tour.golang.org/moretypes/25</a></p> <pre><code>package main import &#34;fmt&#34; func adder() func(int) int { sum := 5 return func(x int) int { sum += x return sum } } func main() { pos, neg := adder(), adder() for i := 0; i &lt; 10; i++ { fmt.Println( pos(i), neg(-2*i), ) } fmt.Println(pos(10)) } </code></pre> <p>I don&#39;t understand why the <code>sum</code> variable in <code>adder()</code> behaves like a static one. Sorry if this is the wrong place to ask such questions</p> <hr/>**评论:**<br/><br/>HereComesDrTran: <pre><p>The example talks about &#34;function closures&#34; which is what is causing what you&#39;re seeing. Here&#39;s some extra reading on it: <a href="http://keshavabharadwaj.com/2016/03/31/closure_golang/" rel="nofollow">http://keshavabharadwaj.com/2016/03/31/closure_golang/</a></p></pre>Maplicant: <pre><p>Off-topic, but this is the ideal website to me. Clean, pretty, no ads and not bloated with JavaScript widgets.</p></pre>HereComesDrTran: <pre><p>Agreed, props to the author for that for sure</p></pre>budkin: <pre><blockquote> <p>In other words, the function defined in the closure ‘remembers’ the environment in which it was created</p> </blockquote> <p>ah, right! thanks! now it makes sense</p></pre>qwer7y: <pre><p>Ahhh. Yes. Thanks a bunch, stranger!</p></pre>9nut: <pre><p><a href="https://golang.org/ref/spec#Function_literals" rel="nofollow">https://golang.org/ref/spec#Function_literals</a></p></pre>ChurroLoco: <pre><p>The reading posting in the comments is good. To add onto those, think what is in the variables of &#39;pos&#39; and &#39;neg&#39; as data and logic together. Both the data and logic in those variables will stay around as long as the variables remain in scope. In this case the will remain until and end of the program since they are in main.</p></pre>

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

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