略微加速

略速 - 互联网笔记

go语言的init函数

2019-03-13 leiting (2074阅读)

标签 Golang

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函数的笔误


http://www.cnblogs.com/youyou/archive/2013/04/21/3034211.html


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3