Answers for "init function in golang"

Go
1

init function in golang

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

func init() {
	fmt.Printf("%v\n", home)
	fmt.Printf("%v\n", user)
	fmt.Printf("%v\n", gopath)
}

func main() {
	fmt.Println("should print this line after executing init function")
}
/**
init function in Golang:
	- 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.
**/
Posted by: Guest on July-04-2021

Browse Popular Code Answers by Language