In Go, it's possible to declare variables with different scopes: local (function scope) and top-level (package or file scope). Occasionally, you may encounter a situation where you want to refer to a top-level constant or variable within the function scope, where a local variable with the same name exists.
Consider the following code snippet:
package main import "fmt" const name = "Yosua" // or var name string = "James" func main() { name := "Jobs" fmt.Println(name) }
Question: How can we refer to the constant name instead of the local variable?
Answer:
Accessing the enclosing scope variable in the presence of a local variable with the same name is not possible. While the local variable is in scope, it shadows the outer variable within the function, making it inaccessible.
The Go language specification states:
An identifier declared in a block may be redeclared in an inner block. While the identifier of the inner declaration is in scope, it denotes the entity declared by the inner declaration.
Alternatives:
If you need to access both the top-level and local variables simultaneously, consider using distinct names. However, if that's not feasible, you can resort to the following alternatives:
Temporarily Assign to a New Variable:
For example:
cname := name name := "Jobs" fmt.Println(name) fmt.Println(cname)
Expose the Top-Level Variable Indirectly:
For example:
func getName() string { return name } name := "Jobs" fmt.Println(name) fmt.Println(getName())
The above is the detailed content of How do I access a top-level constant or variable in Go when a local variable with the same name exists?. For more information, please follow other related articles on the PHP Chinese website!