How do I access a top-level constant or variable in Go when a local variable with the same name exists?

DDD
Release: 2024-11-15 19:40:03
Original
703 people have browsed it

How do I access a top-level constant or variable in Go when a local variable with the same name exists?

Referring to Constant or Package-Level Variables within Function Scope

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)
}
Copy after login

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.
Copy after login

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:

  1. Temporarily Assign to a New Variable:

    • Store the value of the top-level variable in a temporary variable before assigning to the local variable.
    • For example:

      cname := name
      name := "Jobs"
      fmt.Println(name)
      fmt.Println(cname)
      Copy after login
  2. Expose the Top-Level Variable Indirectly:

    • Create a function or method that returns the top-level variable's value.
    • For example:

      func getName() string {
       return name
      }
      
      name := "Jobs"
      fmt.Println(name)
      fmt.Println(getName())
      Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template