免费观看又色又爽又黄的小说免费_美女福利视频国产片_亚洲欧美精品_美国一级大黄大色毛片

golang中的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.

以上就是go語言的init函數詳解的詳細內容,更多請關注創新互聯其它相關文章!

文章標題:golang中的init函數-創新互聯
本文網址:http://newbst.com/article38/dijgsp.html

成都網站建設公司_創新互聯,為您提供網站排名Google網頁設計公司ChatGPT軟件開發企業網站制作

廣告

聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯

微信小程序開發