Home

Init Functions In Go

Created: Dec 15, 2020 8:31 PM

TIL I learned about the init() function in Go. I must have glossed over the init() function when initially learning the language because I just didn't have a need for it. All of the programs I wrote initially to learn the language were all pretty small and focused; any initialization I needed could be done at the beginning of the main() function. Similar to programming with Unity, you can get a lot done by just using the Start() method but it is sometimes useful to use Awake() to better control initialization.

What if you have packages other than the main package? In many circumstances you can tie all your methods to structs in a package and initialize those structs, but you might need to guarantee certain things are initialized when a package is loaded. The init() function is used for just that. init() is called upon package initialization. It is important to know that package initialization only happens once even if a package is imported multiple times. This means that init() will only be called once: the first time a package is loaded. Additionally you cannot call the init() function.