5

Init

 2 years ago
source link: https://linuxsuren.github.io/blog/language/golang/init/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

init 函数定义在包(package)中,并有如下的用处:

  • 初始化变量(无法在初始化表达中完成的)
  • 执行一次性计算

为了使用一个导入的包,首先需要初始化。这是由 Golang 的运行时系统完成,包含如下步骤:

  1. 初始化导入的包(递归)
  2. 计算在包级别申明的变量并赋值
  3. 执行包中的 init 函数
</div>


<div class="admonition-content">

包初始化只会执行一次,即使会被导入多次。

init 函数没有任何参数,也不会返回任何值。而且,它也无法被调用。

init 函数可以定义多次。

只在内部导入包

Go 对于没有用到的包是很严格的。有时候,我们可能希望导入一个包,只是为了调用 init 函数。可以按照如下方式来:

import _ "image/png"


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK