13
聊聊golang的包init
source link: https://studygolang.com/articles/31827
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.
序
本文主要研究一下golang中的包init
包init实例
pkg1
package pkg1 import ( "fmt" ) func init() { fmt.Println("pkg1 init1") } func init() { fmt.Println("pkg1 init2") } func Hello() { fmt.Println("pkg1 hello") }
pkg2
package pkg2 import ( "fmt" "init-demo/pkg3" ) func init() { fmt.Println("pkg2 init1") } func init() { fmt.Println("pkg2 init2") } func World() { fmt.Println("pkg2 world") pkg3.Greet() }
pkg3
package pkg3 import "fmt" func init() { fmt.Println("pkg3 init1") } func init() { fmt.Println("pkg3 init2") } func Greet() { fmt.Println("pkg3 greet") }
main
package main import ( "fmt" "init-demo/pkg1" "init-demo/pkg2" "time" ) func init() { fmt.Println("main init1") } func init() { go func() { fmt.Println("main init2 with go routine") time.Sleep(time.Second * 5) fmt.Println("main init2 finish sleep") }() } func init() { fmt.Println("main init3") } func main() { fmt.Println("main") pkg2.World() pkg1.Hello() time.Sleep(time.Second * 10) }
输出
pkg1 init1 pkg1 init2 pkg3 init1 pkg3 init2 pkg2 init1 pkg2 init2 main init1 main init3 main pkg2 world pkg3 greet pkg1 hello main init2 with go routine main init2 finish sleep
小结
- 每个package可以定义多个init函数,甚至在同一个go文件也可以有多个init函数。
- 如果一个包没有import其他包,则多个init按出现顺序初始化
- 同一个包多个文件都有init函数则按文件名顺序初始化
- 一般go fmt的话,会对import进行排序,这样子保证初始化行为的可再现性
- 如果一个包有import其他包,则按依赖顺序从最里层包开始初始化
doc
有疑问加站长微信联系(非本文作者)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK