go語言的init函數


go語言中init函數用於包(package)的初始化,該函數是go語言的一個重要特性,

有下面的特征:

1 init函數是用於程序執行前做包的初始化的函數,比如初始化包里的變量等

2 每個包可以擁有多個init函數

3 包的每個源文件也可以擁有多個init函數

4 同一個包中多個init函數的執行順序go語言沒有明確的定義(說明)

5 不同包的init函數按照包導入的依賴關系決定該初始化函數的執行順序

6 init函數不能被其他函數調用,而是在main函數執行之前,自動被調用

下面這個示例摘自《the way to go》,os差異在應用程序初始化時被隱藏掉了,

var prompt = "Enter a digit, e.g. 3 " + "or %s to quit."

func init() {
    if runtime.GOOS == "windows" {
        prompt = fmt.Sprintf(prompt, "Ctrl+Z, Enter")
    } else { // Unix-like
        prompt = fmt.Sprintf(prompt, "Ctrl+D")
    }
}

下面的兩個go文件演示了:

 1 一個package或者是go文件可以包含多個init函數,

 2 init函數是在main函數之前執行的,

 3 init函數被自動調用,不能在其他函數中調用,顯式調用會報該函數未定義 

gprog.go代碼

package main

import (
    "fmt"
)

// the other init function in this go source file
func init() {
    fmt.Println("do in init")
}

func main() {
    fmt.Println("do in main")
}

func testf() {
    fmt.Println("do in testf")
    //if uncomment the next statment, then go build give error message : .\gprog.go:19: undefined: init
    //init()
}

ginit1.go代碼,注意這個源文件中有兩個init函數

package main

import (
    "fmt"
)

// the first init function in this go source file
func init() {
    fmt.Println("do in init1")
}

// the second init function in this go source file
func init() {
    fmt.Println("do in init2")
}

編譯上面兩個文件:go build gprog.go ginit1.go

編譯之后執行gprog.exe后的結果表明,gprog.go中的init函數先執行,然后執行了ginit1.go中的兩個init函數,然后才執行main函數。

E:\opensource\go\prj\hellogo>gprog.exe
do in init
do in init1
do in init2
do in main

注:《the way to go》中(P70)有下面紅色一句描述,意思是說一個go源文件只能有一個init函數,

      但是上面的ginit1.go中的兩個init函數編譯運行后都正常執行了,

      因此這句話應該是筆誤。

4.4.5 Init-functions
Apart from global declaration with initialization, variables can also be initialized in an init()-function.
This is a special function with the name init() which cannot be called, but is executed automatically
before the main() function in package main or at the start of the import of the package that
contains it.
Every source file can contain only 1 init()-function. Initialization is always single-threaded and
package dependency guarantees correct execution order.

 

2013.04.21 初稿

2013.04.23 補充說明《the way to go》 中關於init函數的筆誤

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM