Golang Init Function

When is the init function called?

  • After all the variable declarations in the package have evaluated their initializers.
  • Only after all the imported packages have been initialized.

Order of package initialization

  1. initialization of imported packages (recursive definition)
  2. computing and assigning initial values for variables declared in a package block
  3. executing init functions inside the package

Usecase of init function

Other tips about the init function

  • Many init functions can be defined in the same package or file

Reference