go语言的init函数详解

发布时间:2022-05-15 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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.

推荐:go视频教程

以上就是go语言的init函数详解的详细内容,更多请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的go语言的init函数详解全部内容,希望文章能够帮你解决go语言的init函数详解所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: