Refer to constant or package level variable instead of function level variable

瘦欲@ 提交于 2019-12-18 09:26:32

问题


package main

import "fmt"

const name = "Yosua"
// or var name string = "James"

func main() {
    name := "Jobs"
    fmt.Println(name)
}

How to refer to the constant and not the the function level variable?


回答1:


You can't. While the local variable name is in scope, the name name denotes the local variable. And there is no "qualifier" to refer to top-level identifiers.

Spec: Declarations and scope:

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.

If you need to access both the top-level constant/variable and the local variable at the same time, use different names.

If for some reason you can't or don't want to, you may save the value of the top-level constant or variable first:

cname := name
name := "Jobs"
fmt.Println(name)
fmt.Println(cname)

Or you may provide other means to access it, e.g. a function:

func getName() string {
    return name
}

name := "Jobs"
fmt.Println(name)
fmt.Println(getName())

Output in both cases (try them on the Go Playground):

Jobs
Yosua


来源:https://stackoverflow.com/questions/38496954/refer-to-constant-or-package-level-variable-instead-of-function-level-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!