How to use "this" (like in java) that refer global variable?

xuanbao · · 503 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<pre><code>package main import ( &#34;fmt&#34; ) var name string = &#34;Josh&#34; func main() { var name string = &#34;Ben&#34; fmt.Println(name) // Ben // PROBLEM: How to print variable that Josh inside? } </code></pre> <hr/>**评论:**<br/><br/>lapingvino: <pre><p>the {} introduces a new scope, and the name in the main function shadows the outside name. What you should do here instead is consciously avoid using the same name. Also, you could create a top level struct called e.g. &#34;global&#34; that has a field &#34;name&#34;. You can really do that however you want, but keep in mind that avoiding globals can spare you a lot of problems ;).</p></pre>mc_hammerd: <pre><p>yea. one alternative is a &#39;trick&#39; c programmers use sometimes. put everything global in a global struct. ex: <a href="http://play.golang.org/p/3JyD_cXvxe" rel="nofollow">http://play.golang.org/p/3JyD_cXvxe</a></p></pre>nicerobot: <pre><pre><code>package main import &#34;fmt&#34; var name = &#34;Josh&#34; func main() { globalname, name := name, &#34;Ben&#34; fmt.Println(&#34;Hello &#34;,name,&#34;and&#34;,globalname) } </code></pre> <p>The point here is that you recognize you are explicitly changing the <code>name</code> variable to a different scope yet still intend to use the global <code>name</code> too.</p></pre>dazzford: <pre><p>Others have given you workarounds but the real solution is to not use global variables. </p> <p>They are an anti-pattern and a code smell.</p></pre>

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

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