The init()
function serves as a unique package initializer in the Go language.
An init()
function is package-scoped, and we can use it to set up our application state before entering into the main()
function. It is invoked sequentially in a single Goroutine
, along with other global variable initializations.
We can declare the init
function with the init
identifier.
func init() { }
The init
function doesn’t take any arguments.
The init
function doesn’t return any results.
The
init
identifier is not declared, so we cannot refer to it from inside the program.
package mainimport "fmt"func init(){fmt.Printf("Invoked init()\n")}func main() {fmt.Printf("Executing main()\n")}
init
function is invoked prior to the main
function.init()
functionsWe can define multiple init()
functions in Go. We can even have multiple init
functions in a single file. They’ll be invoked sequentially in the order that they appear.
package mainimport "fmt"var foo = varInit()func varInit() string{fmt.Printf("initialized foo\n")return "foo"}func init(){fmt.Printf("First init()\n")}func init(){fmt.Printf("Second init()\n")}func main() {fmt.Printf(foo)}
foo
before calling the init
function. The current init()
will complete before the next init()
is invoked.The imported packages will get initialized before the current one. Every package is initialized only once.
The init
functions defined in different files will be invoked as they are presented to the compiler. Mostly, this is in the lexical order of the file names.
Free Resources