When is the init() function run?

Technology CommunityCategory: GolangWhen is the init() function run?
VietMX Staff asked 3 years ago

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.

If a package has one or more init() functions they are automatically executed before the main package’s main() function is called.

import --> const --> var --> init()
  • If a package imports other packages, the imported packages are initialized first.
  • Current package’s constant initialized then.
  • Current package’s variables are initialized then.
  • Finally, init() function of current package is called.