golang中init函数调用的相关顺序

原文链接

如下代码块中会会优先调用AnswerToLife函数运行,之后调用init函数进行初始化,确保在调用main之前会调用init函数,同时多个package可以有多个init函数(是每个package的多个function允许有一个init呢还是每个package只允许有一个呢)

文章原文:

Yes assuming you have this:

<span class="kwd">var</span> <span class="typ">WhatIsThe</span> <span class="pun">=</span> <span class="typ">AnswerToLife</span><span class="pun">()</span><span class="pln">

func </span><span class="typ">AnswerToLife</span><span class="pun">()</span> <span class="kwd">int</span> <span class="pun">{</span>
    <span class="kwd">return</span> <span class="lit">42</span>
<span class="pun">}</span><span class="pln">

func init</span><span class="pun">()</span> <span class="pun">{</span>
    <span class="typ">WhatIsThe</span> <span class="pun">=</span> <span class="lit">0</span>
<span class="pun">}</span><span class="pln">

func main</span><span class="pun">()</span> <span class="pun">{</span>
    <span class="kwd">if</span> <span class="typ">WhatIsThe</span> <span class="pun">==</span> <span class="lit">0</span> <span class="pun">{</span><span class="pln">
        fmt</span><span class="pun">.</span><span class="typ">Println</span><span class="pun">(</span><span class="str">"It's all a lie."</span><span class="pun">)</span>
    <span class="pun">}</span>
<span class="pun">}</span>

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