Initialization Function of a Package
Before explaining anonymous import, let's introduce the initialization function of a package, init()
.
When a program is executed, the internal init
function is automatically triggered. Note that init()
is an optional function. For example, the helloWorld
program we wrote earlier did not have an init
function.
The points to note about the init
function are as follows:
- The init function has no parameters and does not return any values.
- You cannot actively call it in your code.
Note: The usage of fmt.Print()
is similar to fmt.Println()
. It does not automatically break lines after output, as we will explain in later sections.
You can see that the initializer function init()
runs before the main
function in a program and after global declarations.
What about consecutive calls to multiple packages? Suppose our main
package calls the fmt
package, and the fmt
package calls the io
package, which in turn calls the error
package.
Assuming each package has its own initialization function, what is the execution order?
In Go, the compiler starts from the main
package and gradually checks subsequent packages, constructing a stack data structure.
During runtime, the initialization function is executed in the reverse order of the packages imported last, as shown in the following diagram: