Go init() function


任何檔案可以擁有任意數量的 init() function:

func init() {
    // ...
}

init() 會在程式啟動時自動以宣告的順序執行,但不能被 call 或參考。

假設有以下兩個 go 檔案:

foo.go

package main

import "fmt"

func init() {
    fmt.Println("foo.go first init")
}

main.go

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 會有不同結果:

$ 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:

package main

import "fmt"

func init() {
    fmt.Println("main.go first init")
}

func main() {
    init()  // compile error: undefined: init
}
#GO






你可能感興趣的文章

PHP會員管理系統 - 超入門版登入串接

PHP會員管理系統 - 超入門版登入串接

來學 React 吧之八_部署 React App

來學 React 吧之八_部署 React App

JQ總務處|點擊空白處關閉漢堡選單

JQ總務處|點擊空白處關閉漢堡選單






留言討論