What are init functions in Go?
Overview
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.
Syntax
func init() { }
Parameters
The init function doesn’t take any arguments.
Return value
The init function doesn’t return any results.
The
initidentifier is not declared, so we cannot refer to it from inside the program.
Demo code
package mainimport "fmt"func init(){fmt.Printf("Invoked init()\n")}func main() {fmt.Printf("Executing main()\n")}
Explanation
- The
initfunction is invoked prior to themainfunction.
Defining multiple init() functions
We 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)}
Explanation
- On line 4, we initialize the global variable
foobefore calling theinitfunction. The currentinit()will complete before the nextinit()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