问题描述
以下是有问题的代码段:
Here is the code snippet in question:
package main
import (
"fmt"
)
var a string = "hello"
func main() {
b := "world"
fmt.Println(a, b)
a := "bye"
fmt.Println(a, b)
}
输出:
hello world
bye world
我的问题是,如何解决全局"和局部"变量a
之间的名称冲突?
My question is, how do I resolve name clash between the "global" and "local" variables a
?
更具体地说,如何告诉Go使用哪个a
?
More specifically, how do I tell Go which a
to use?
推荐答案
我认为您的原始示例很好地说明了这种情况.就像大多数编程语言一样,范围也很重要.
I think your original example illustrates the situation well. Just like most in programming languages the scope matters.
最接近用途的范围决定了a
的值.因此,如果您在函数内部重新声明(:=
)变量,则在该函数的持续时间内,您将拥有值"bye"
.
The scoping closest to the use is what decides the value of a
. So if you redeclare (:=
) the variable inside your function, then for the duration of that function you will have the value "bye"
.
如果您选择在两个事物上使用相同的名称,则结果是内部名称将始终占主导地位.如果您需要两个值,请分别为变量命名.
If you chose to use the same name for two things, the consequence is that the inner name will always dominate. If you need both values then name the variables differently.
这篇关于全局和局部变量名冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!