[Introduction]init函数:初始化

251 阅读1分钟

init函数

init()函数实现一些包级别的初始化操作,不能被其他函数调用,且没有参数和返回值

示例:

package main

import (
	"log"
)

func Init() {
	log.Println("this is Init func")
}

func init() {
	log.Println("this is init func")
}

func main() {
	Init()
	log.Println("this is main func")
	// init() undefined: init
}

运行结果:

2020/07/13 10:15:34 this is init func
2020/07/13 10:15:34 this is Init func
2020/07/13 10:15:34 this is main func

初始化

在对链接进行初始化及其他初始化操作的时候,建议使用Init()函数显式调用避免init函数的未知行为

参考链接

五分钟理解golang的init函数

Initialize function in Golang