34

init()函数

 5 years ago
source link: https://studygolang.com/articles/15214?amp%3Butm_medium=referral
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.

init()函数优先于main()函数执行

每个源文件都可以包含一个init函数,这个init函数自动被go运行框架调用,执行的优先级最高。

让我们做一个代码来验证一下:

·目录结构:

|-example2
	|-initInfo
		|-initInfo.go
	|-students
		|-students.go
	|-example2.go

students---students.go:

package students

import _ "oldboy/listen2/example2/initInfo"

var Name string
var Age int

func init() {
	Name = "shengj"
	Age = 10
}

initInfo---initInfo.go

package initInfo

import "fmt"

func init() {
	fmt.Println("This is Info init")
}

example2.go:

package initInfo

import "fmt"

func init() {
	fmt.Println("This is Info init")
}

我们可以看到在students.student.go中有一个很有意思的操作: import _ "oldboy/listen2/example2/initInfo" 我们虽然引入了这个包,但是我们并没有使用这个包中的任何东西,所以我们用_将这个包”隐藏了“,即

利用_可以完成包的只初始化,不引用。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK