当前位置:   article > 正文

golang 全局变量_Golang:模块初始化

golang全局变量初始化

预计阅读时间——15分钟

1074d3be0a382ef19cac5d938c64b27e.png

南京总统府

一般来说,我们通常会讲Go程序的入口函数是main,是否还有比main函数更早得到运行的函数呢?

这篇文档就会讲到关于初始化函数init,尽量言简意赅以例子的形式展开。

init函数

Finally, each source file can define its own niladic init function to set up whatever state is required. (Actually each file can have multiple init functions.) 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.
Besides initializations that cannot be expressed as declarations, a common use of init functions is to verify or repair correctness of the program state before real execution begins.

每个模块都可以有一个或者多个init函数,它们的特性和作用是:

  • init函数的signature是无参数,无返回值
  • 初始化模块(文件)中全局变量声明无法初始化的复杂类型:map,slice,array等
  • 模块中仅执行一次的操作,如:数据库初始化,cache初始化,读取配置文件等
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/574339
推荐阅读
相关标签
  

闽ICP备14008679号