dongyong2063 2018-09-17 14:49
浏览 48
已采纳

进行全局变量初始化

Issue on loading the configuration on file scope global variable.

The config setting and and loading config values inside main method

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  

}

my config setting. config.go

var appConfig AppConfig

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

func GetConfig() AppConfig {
    return appConfig
}

I have another service file with global variable defined inside service.go

   var x = config.GetConfig().Value

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

Question:

Why my global variable x inside service.go is not initialized ?

Thanks

  • 写回答

2条回答 默认 最新

  • doubi7739 2018-09-17 15:01
    关注

    Per the Go specification, the order of execution is as follows:

    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.

    Meaning the order is roughly:

    1. Global variables get initialized
    2. init() functions run
    3. main() runs

    So your global initialization is happening before main() has a chance to load your configuration.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素