When is the init() function run?

前端 未结 11 676
离开以前
离开以前 2020-12-02 03:41

I\'ve tried to find a precise explanation of what the init() function does in Go. I read what Effective Go says but I was unsure if I understood fully what it s

11条回答
  •  爱一瞬间的悲伤
    2020-12-02 03:52

    Here is another example - https://play.golang.org/p/9P-LmSkUMKY

    package main
    
    import (
        "fmt"
    )
    
    func callOut() int {
        fmt.Println("Outside is beinge executed")
        return 1
    }
    
    var test = callOut()
    
    func init() {
        fmt.Println("Init3 is being executed")
    }
    
    func init() {
        fmt.Println("Init is being executed")
    }
    
    func init() {
        fmt.Println("Init2 is being executed")
    }
    
    func main() {
        fmt.Println("Do your thing !")
    }
    

    Output of the above program

    $ go run init/init.go
    Outside is being executed
    Init3 is being executed
    Init is being executed
    Init2 is being executed
    Do your thing !
    

提交回复
热议问题