funcconstInitCheck()string { if c1 != "" { fmt.Println("main: const c1 has been initialized") } if c2 != "" { fmt.Println("main: const c2 has been initialized") } return"" }
funcvariableInit(name string)string { fmt.Printf("main: var %s has been initialized\n", name) return name }
funcinit() { fmt.Println("main: first init func invoked") }
funcinit() { fmt.Println("main: second init func invoked") }
funcmain() { fmt.Println("main: main func invoked") }
$ ./go101 pkg3: const c1 has been initialized pkg3: const c2 has been initialized pkg3: var v1 has been initialized pkg3: var v2 has been initialized pkg3: first init func invoked pkg3: second init func invoked pkg1: const c1 has been initialized pkg1: const c2 has been initialized pkg1: var v1 has been initialized pkg1: var v2 has been initialized pkg1: first init func invoked pkg1: second init func invoked pkg2: const c1 has been initialized pkg2: const c2 has been initialized pkg2: var v1 has been initialized pkg2: var v2 has been initialized pkg2: first init func invoked pkg2: second init func invoked main: const c1 has been initialized main: const c2 has been initialized main: var v1 has been initialized main: var v2 has been initialized main: first init func invoked main: second init func invoked main: main func invoked
Go 包初始化顺序
依赖包之间按照深度优先的次序进行初始化
依赖包之内按照常量、变量、init 函数的顺序进行初始化
依赖包之内的多个 init 函数按照声明次序进行自动调用
用途
重置包级变量值
负责对包内部以及暴露到外部的包级数据(主要是包级变量)的初始状态进行检查
flag 包定定义了一个 Exported 包级变量 CommandLine flag 包初始化时,包级变量 CommandLine 在 init 函数之前就被初始化了