问题
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)
}
Output:
hello world
bye world
My question is, how do I resolve name clash between the "global" and "local" variables a
?
More specifically, how do I tell Go which a
to use?
回答1:
I think your original example illustrates the situation well. Just like most in programming languages the scope matters.
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.
回答2:
Well, this is not really a solution but a workaround. Before creating a shadowning variable, you can make a pointer to an outside variable.
var a string = "hello"
func main() {
b := "world"
fmt.Println(a, b)
pa := &a
a := "bye"
fmt.Println(*pa, b, a)
}
回答3:
This is called variable shadowing. You just name them differently.
You can't just ask go to behave differently.
来源:https://stackoverflow.com/questions/47624326/clashing-global-and-local-variable-name