douerqu2319 2014-07-16 20:34
浏览 1339
已采纳

init()函数何时运行?

I've tried to find a precise explanation of what the init() function does in Go. I read what Effective Go says but I was unsure if I understood fully what it said. The exact sentence I am unsure is the following:

And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.

What does all the variable declarations in the package have evaluated their initializers mean? Does it mean if you declare "global" variables in a package and its files, init() will not run until all of it is evaluated and then it will run all the init function and then main() when ./main_file_name is ran?

I also read Mark Summerfield's go book the following:

If a package has one or more init() functions they are automatically executed before the main package's main() function is called.

In my understanding, init() is only relevant when you run intend to run main() right? or the Main package. Anyone understands more precisely init() feel free to correct me

  • 写回答

9条回答 默认 最新

  • dongre6270 2014-07-16 20:46
    关注

    Yes assuming you have this:

    var WhatIsThe = AnswerToLife()
    
    func AnswerToLife() int {
        return 42
    }
    
    func init() {
        WhatIsThe = 0
    }
    
    func main() {
        if WhatIsThe == 0 {
            fmt.Println("It's all a lie.")
        }
    }
    

    AnswerToLife() is guaranteed to run before init() is called, and init() is guaranteed to run before main() is called.

    Keep in mind that init() is always called, regardless if there's main or not, so if you import a package that has an init function, it will be executed.

    Additionally, you can have multiple init() functions per package; they will be executed in the order they show up in the file (after all variables are initialized of course). If they span multiple files, they will be executed in lexical file name order (as pointed out by @benc):

    It seems that init() functions are executed in lexical file name order. The Go spec says "build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler". It seems that go build works this way.


    A lot of the internal Go packages use init() to initialize tables and such, for example https://github.com/golang/go/blob/883bc6/src/compress/bzip2/bzip2.go#L480

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

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler