How to modify $variable defined outside of range loop in templates?

agolangf · · 492 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p><a href="http://play.golang.org/p/jy7hDD9QXF">http://play.golang.org/p/jy7hDD9QXF</a></p> <p>Is it possible to make this program print</p> <pre><code>1 2 3 </code></pre> <p>?</p> <hr/>**评论:**<br/><br/>djherbis: <pre><p>You could move the state inside a struct, and pass the methods as functions:</p> <p><a href="http://play.golang.org/p/XGcSsrCywx" rel="nofollow">http://play.golang.org/p/XGcSsrCywx</a></p></pre>gohacker: <pre><p>That&#39;s exactly what I came up with first, but then I noticed that it&#39;s not goroutine safe.</p></pre>djherbis: <pre><p>If you want independent state for each instance of template, have each template generate their own state. </p> <p><a href="http://play.golang.org/p/xDiQ_kjhKW" rel="nofollow">http://play.golang.org/p/xDiQ_kjhKW</a></p> <p>(to be clear, since no state is shared across template instances it must be go-routine safe)</p></pre>HectorJ: <pre><p>That got asked several times on StackOverflow already (example: <a href="http://stackoverflow.com/q/33027070/1685538" rel="nofollow">http://stackoverflow.com/q/33027070/1685538</a>)</p> <p>The idea is that this logic does not belong in a template.</p> <p>That&#39;s sometimes a bit frustrating, but in the same time understandable...</p></pre>_medved_: <pre><p>There&#39;s no way, variables can only be assigned to once.</p></pre>gohacker: <pre><blockquote> <p>variables can only be assigned to once.</p> </blockquote> <p><a href="http://play.golang.org/p/t93vLHG7Rh" rel="nofollow">Are you sure?</a></p></pre>WOFall: <pre><p>Ah, but those are different variables with the same name ;)</p></pre>

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

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