【Golang】初始化(Initialisation)

Posted by 西维蜀黍 on 2020-08-02, Last Modified on 2023-08-23

Constants

Variables

Variables can be initialized just like constants but the initializer can be a general expression computed at run time.

var (
    home   = os.Getenv("HOME")
    user   = os.Getenv("USER")
    gopath = os.Getenv("GOPATH")
)

The init function

Finally, each source file can define its own niladic(无参数的) init function to set up whatever state is required. (Actually each file can have multiple init functions.)

And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.

Besides initializations that cannot be expressed as declarations, a common use of init functions is to verify or repair correctness of the program state before real execution begins.

func init() {
    if user == "" {
        log.Fatal("$USER not set")
    }
    if home == "" {
        home = "/home/" + user
    }
    if gopath == "" {
        gopath = home + "/go"
    }
    // gopath may be overridden by --gopath flag on command line.
    flag.StringVar(&gopath, "gopath", gopath, "override default GOPATH")
}

不用的包不会被import

$ tree
├── sw_pprof
│   ├── a
│   │   ├── a1.go
│   │   ├── a2.go
│   │   └── subA
│   │       └── subA_a1.go
│   ├── b
│   │   └── b1.go
│   └── sw_pprof.go

sw_pprof.go 中 import了 GoPlayGround/sw_pprof/a ,但是没有 import GoPlayGround/sw_pprof/a/subA。这是 subA 下的 init() 不会被调用。

Reference