请参阅常量或包级变量而不是函数级变量 [英] Refer to constant or package level variable instead of function level variable

查看:145
本文介绍了请参阅常量或包级变量而不是函数级变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  package main 

importfmt

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

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

$ b

如何引用常量而不是函数级变量?

解决方案

你不能。虽然局部变量 name 在范围内,但名称 name 表示局部变量。并且没有限定符来指代顶级标识符。



规范:声明和范围:


块中声明的标识符可以在内部重新声明块。虽然内部声明的标识符在范围内,但它表示由内部声明声明的实体。


如果您需要同时访问顶级常量/变量和局部变量同时使用不同的名字。



如果由于某种原因你不能或不想,您可以先保存顶层常量或变量的值:

  cname:= name 
name:= 作业
fmt.Println(名称)
fmt.Println(cname)



<或者您可以提供其他方式来访问它,例如一个函数:

  func getName()字符串{
返回名称
}

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

在这两种情况下输出(在去游乐场试试):

 工作
Yosua


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?

解决方案

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

这篇关于请参阅常量或包级变量而不是函数级变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆