<p>I have a question about setting global variables with the shorthand := in Golang.</p>
<p>I wrote the following code as a demo:</p>
<pre><code>var str = "Old Value!"
func main() {
str, err := foo()
if err != nil {
// There will never be an error
log.Println(err)
}
fmt.Println(str) // Prints "New Value!"
printStr() // Prints "Old Value!"
}
func foo() (string, error) {
return "New Value!", nil
}
func printStr() {
fmt.Println(str)
}
</code></pre>
<p>And the output is:</p>
<pre><code>New Value!
Old Value!
</code></pre>
<p>My question is, how can I replace the value of the global var <strong>str</strong> with the result of <strong>foo()</strong>? Would I need to do something like:</p>
<pre><code>var err error
str, err = foo()
</code></pre>
<p><strong>Are there any methods or is this the only one?</strong></p>
<hr/>**评论:**<br/><br/>deusmetallum: <pre><p>Yes, this is the correct thing to do.</p>
<pre><code>var err error
str, err = foo()
</code></pre></pre>throwlikepollock: <pre><p>I usually do the opposite, eg:</p>
<p>s,err := foo()
str = s</p>
<p>Is one more idiomatic than the other?</p>
<p>Pardon for formatting, on phone</p></pre>SilentWeaponQuietWar: <pre><p>why assign the string result from foo() twice? (once into s, and again from s into str)?</p></pre>niosop: <pre><p>Because s is only going to be in scope inside main. To be visible from printStr, it needs to get put into the str global. Since using str, err := will cause a locally scoped str variable to be created, the global str will not be modified. So you either explicitly declare err and use =, or use := and copy the result into the global variable.</p>
<p>edit: Or, preferably, don't use a global at all and just pass the string to printStr. But this seems more a discussion of how shadowning works with :=</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传