如何引用常量而不是函数级变量?
解决方案你不能。虽然局部变量 name 在范围内,但名称 name 表示局部变量。并且没有限定符来指代顶级标识符。
规范:声明和范围:
块中声明的标识符可以在内部重新声明块。虽然内部声明的标识符在范围内,但它表示由内部声明声明的实体。
如果您需要同时访问顶级常量/变量和局部变量同时使用不同的名字。
如果由于某种原因你不能或不想,您可以先保存顶层常量或变量的值:
cname:= name name:= 作业 fmt.Println(名称) fmt.Println(cname)<或者您可以提供其他方式来访问它,例如一个函数:
func getName()字符串{返回名称} name:=Jobs fmt.Println(name) fmt.Println(getName())在这两种情况下输出(在去游乐场试试):
工作 Yosuapackage 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?
解决方案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
更多推荐
请参阅常量或包级变量而不是函数级变量
发布评论