When is the init() function run?

前端 未结 11 686
离开以前
离开以前 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 04:08

    Something to add to this (which I would've added as a comment but the time of writing this post I'd not yet enough reputation)

    Having multiple inits in the same package I've not yet found any guaranteed way to know what order in which they will be run. For example I have:

    package config
        - config.go
        - router.go
    

    Both config.go and router.go contain init() functions, but when running router.go's function ran first (which caused my app to panic).

    If you're in a situation where you have multiple files, each with its own init() function be very aware that you aren't guaranteed to get one before the other. It is better to use a variable assignment as OneToOne shows in his example. Best part is: This variable declaration will happen before ALL init() functions in the package.

    For example

    config.go:

    var ConfigSuccess = configureApplication()
    
    func init() {
        doSomething()
    }
    
    func configureApplication() bool {
        l4g.Info("Configuring application...")
        if valid := loadCommandLineFlags(); !valid {
            l4g.Critical("Failed to load Command Line Flags")
            return false
        }
        return true
    }
    

    router.go:

    func init() {
        var (
            rwd string
            tmp string
            ok  bool
        )
        if metapath, ok := Config["fs"]["metapath"].(string); ok {
            var err error
            Conn, err = services.NewConnection(metapath + "/metadata.db")
            if err != nil {
                panic(err)
            }
        }
    }
    

    regardless of whether var ConfigSuccess = configureApplication() exists in router.go or config.go, it will be run before EITHER init() is run.

提交回复
热议问题