gpt4 book ai didi

go - 引用常量或包级变量而不是函数级变量

转载 作者:IT王子 更新时间:2023-10-29 01:50:12 26 4
gpt4 key购买 nike

package main

import "fmt"

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

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

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

最佳答案

你不能。当局部变量 name 在范围内时,名称 name 表示局部变量。并且没有“限定符”来引用顶级标识符。

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.

如果您需要同时访问顶层常量/变量和局部变量,请使用不同的名称。

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

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

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

func getName() string {
return name
}

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

两种情况下的输出(在 Go Playground 上尝试):

Jobs
Yosua

关于go - 引用常量或包级变量而不是函数级变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38496954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com