Home > Article > Backend Development > How to Access Constants and Package-Level Variables When Shadowed by Local Variables in Go?
In the provided Go code, within the main function, a local variable name is defined, which shadows the constant or package-level variable with the same name. This can lead to confusion and incorrect behavior.
In Go, when a new variable is declared within a function, it takes precedence over any other variable with the same name defined at a higher level (e.g., in a package-level scope). This is known as variable shadowing.
To refer to the constant or package-level variable name within the main function, we can't directly use the identifier name as it denotes the function-level variable. Instead, we can use one of the following approaches:
const name = "Yosua" func main() { localName := name name := "Jobs" fmt.Println(name) // Jobs fmt.Println(localName) // Yosua }
const name = "Yosua" func getName() string { return name } func main() { name := "Jobs" fmt.Println(name) // Jobs fmt.Println(getName()) // Yosua }
If a package-level variable is declared using var instead of const, it can be shadowed and reassigned within functions. In such cases, using one of the approaches above ensures that the original value is preserved.
The above is the detailed content of How to Access Constants and Package-Level Variables When Shadowed by Local Variables in Go?. For more information, please follow other related articles on the PHP Chinese website!