<pre><code>package main
import (
"fmt"
)
var name string = "Josh"
func main() {
var name string = "Ben"
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. "global" that has a field "name". 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 'trick' 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 "fmt"
var name = "Josh"
func main() {
globalname, name := name, "Ben"
fmt.Println("Hello ",name,"and",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
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传