10.24 2014-07-16 20:34 采纳率: 0%
浏览 731
已采纳

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

转载于:https://stackoverflow.com/questions/24790175/when-is-the-init-function-run

  • 写回答

9条回答 默认 最新

  • Didn"t forge 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.

    //edit

    Also, keep in mind that you can have multiple init() functions per package, they will be executed in the order they show up in the code (after all variables are initialized of course).

    //edit 2x

    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

    //edit 3x

    Multiple inits in the same package execution order 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.

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

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常