Golang 学习笔记

Golang 初始化流程

2018-10-24  本文已影响28人  与蟒唯舞

规则:

案例1

sandbox.go

package main

import "fmt"

var _ int64 = s()

func init() {
    fmt.Println("init in sandbox.go")
}
func s() int64 {
    fmt.Println("calling s() in sandbox.go")
    return 1
}
func main() {
    fmt.Println("main")
}

a.go

package main

import "fmt"

var _ int64 = a()

func init() {
    fmt.Println("init in a.go")
}
func a() int64 {
    fmt.Println("calling a() in a.go")
    return 2
}

z.go

package main

import "fmt"

var _ int64 = z()

func init() {
    fmt.Println("init in z.go")
}
func z() int64 {
    fmt.Println("calling z() in z.go")
    return 3
}

执行命令:
$ go run *.go

输出结果:

calling a() in a.go
calling s() in sandbox.go
calling z() in z.go
init in a.go
init in sandbox.go
init in z.go
main
案例2

sandbox.go

package main

import "fmt"

func init() {
    fmt.Println("init 1")
}
func init() {
    fmt.Println("init 2")
}
func main() {
    fmt.Println("main")
}

utils.go

package main

import "fmt"

func init() {
    fmt.Println("init 3")
}

执行命令:
$ go run *.go

输出结果:

init 1
init 2
init 3
main
上一篇下一篇

猜你喜欢

热点阅读