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


 

转载请注明来源链接 http://just4fun.im/2017/01/22/golang-e4-b8-adinit-e5-87-bd-e6-95-b0-e8-b0-83-e7-94-a8-e7-9a-84-e7-9b-b8-e5-85-b3-e9-a1-ba-e5-ba-8f/ 尊重知识,谢谢:)