请参阅常量或包级变量而不是函数级变量

编程入门 行业动态 更新时间:2024-10-10 17:33:34
本文介绍了请参阅常量或包级变量而不是函数级变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

package main importfmt const name =Yosua // var name name string =James func main(){ name:=Jobs fmt.Println(name)} 如何引用常量而不是函数级变量?

解决方案

你不能。虽然局部变量 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

更多推荐

请参阅常量或包级变量而不是函数级变量

本文发布于:2023-11-23 04:22:34,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   常量   函数   而不是

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!