Home > Backend Development > Golang > How to Access Package-Level or Constant Variables When Shadowed in Go?

How to Access Package-Level or Constant Variables When Shadowed in Go?

Barbara Streisand
Release: 2024-11-22 11:40:11
Original
916 people have browsed it

How to Access Package-Level or Constant Variables When Shadowed in Go?

Referencing Constants and Package-Level Variables Over Function-Level Variables

In Go, it is common to use shadowing to declare variables or constants with the same name within different scopes. While this can be useful, there are times when you need to refer to the original constant or package-level variable instead of the function-level variable.

Unfortunately, in Go, it is not possible to directly refer to the constant or package-level variable when a local variable with the same name exists. This is due to the concept of scope and the Go compiler's preference for local variables over higher-level declarations.

To access the original constant or package-level variable, you need to use alternative techniques. One approach is to store the value in a temporary variable before reassigning the local variable:

cname := name
name = "Jobs"
fmt.Println(name) // Prints "Jobs"
fmt.Println(cname) // Prints "Yosua"
Copy after login

Another option is to create a function that provides access to the constant or package-level variable:

func getName() string {
    return name
}

name = "Jobs"
fmt.Println(name) // Prints "Jobs"
fmt.Println(getName()) // Prints "Yosua"
Copy after login

By using these techniques, you can access both the local variable and the original constant or package-level variable simultaneously. However, it is worth noting that these workarounds may not always be the most elegant or efficient solution, and careful consideration should be given to avoid naming conflicts in your code.

The above is the detailed content of How to Access Package-Level or Constant Variables When Shadowed in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template