任何檔案可以擁有任意數量的 init()
function:
init()
會在程式啟動時自動以宣告的順序執行,但不能被 call 或參考。
假設有以下兩個 go 檔案:
foo.go1 2 3 4 5 6 7
| package main
import "fmt"
func init() { fmt.Println("foo.go first init") }
|
main.go1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package main
import "fmt"
func init() { fmt.Println("main.go first init") }
func init() { fmt.Println("main.go second init") }
func main() {
}
|
在 go run
以不同的順序指定 source file 會有不同結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| $ go run foo.go main.go foo.go first init main.go first init main.go second init
$ go run main.go foo.go main.go first init main.go second init foo.go first init
# 不指定 file $ go run . foo.go first init main.go first init main.go second init
|
不指定 file 的話 go
會將 file 以其名稱排序。
如果嘗試直接 call init()
則會 compile error:
1 2 3 4 5 6 7 8 9 10 11
| package main
import "fmt"
func init() { fmt.Println("main.go first init") }
func main() { init() }
|