gpt4 book ai didi

去全局变量初始化

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:35 27 4
gpt4 key购买 nike

加载文件范围全局变量配置的问题。

主要方法中的配置设置和加载配置值

func main() {

if err := config.LoadConfig(); err != nil {
logrus.Info("Unable to read config : ")
os.Exit(-1)
}

fmt.Println(config.GetConfig().Value) // print the correct value

service.Test() // prints 0

}

我的配置设置。配置.go

var appConfig AppConfig

func LoadConfig() error {
// loads config
appConfig = ....
}

func GetConfig() AppConfig {
return appConfig
}

我有另一个服务文件,在 service.go 中定义了全局变量

   var x = config.GetConfig().Value

func Test(){
fmt.Println(x)
}

问题:

为什么我的 service.go 中的全局变量 x 没有初始化?

谢谢

最佳答案

根据 the Go specification ,执行顺序如下:

Package initialization—variable initialization and the invocation of init functions—happens in a single goroutine, sequentially, one package at a time. An init function may launch other goroutines, which can run concurrently with the initialization code. However, initialization always sequences the init functions: it will not invoke the next one until the previous one has returned.

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

意思顺序大致是:

  1. 全局变量初始化
  2. init() 函数运行
  3. main() 运行

因此您的全局初始化发生在 main() 有机会加载您的配置之前。

关于去全局变量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52370420/

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