理解读懂 Golang init 函数执行顺序

Golang init 函数是一种特殊的函数,主要用于完成程序的初始化工作,如初始化数据库的连接、载入本地配置文件、根据命令行参数初始化全局变量等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import "flag"

var gopath string

func init() {
println("init a")
}

func init() {
println("init b")
}

func init() {
println("init c")
// gopath may be overridden by --gopath flag on command line.
flag.StringVar(&gopath, "gopath", "/root/go", "override default GOPATH")
}

func main() {
println("main")
flag.Parse()
println(gopath)
}

运行输出:

1
2
3
4
5
6
$ go run main.go --gopath="/home/alice/go"
init a
init b
init c
main
/home/alice/go

之所以特殊,是因为 init 函数有如下特点:

参考资料

理解读懂 Golang init 函数执行顺序

https://blog.jiejaitt.top/posts/74a5ec07.html

作者

JIeJaitt

发布于

2021-06-28

更新于

2023-08-30

许可协议

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×