This question may be opinion based, but using several of the init() package functions can make it easier to read and maintain your code.
If your source files are large, you usually place their contents (such as types, variable declarations, methods, etc.) in some logical order. Enabling multiple init() functions allows you to place the initialization code next to the parts that they must initialize. If this is not resolved, you will be forced to use one init() function for each package and put everything in it, away from the variables they need to initialize.
Yes, having multiple init() functions may require some care about the execution order, but be aware that using multiple init() functions is not a requirement, but just an opportunity. And you can write init() functions so that there are no "side" effects, so as not to rely on the completion of other init() functions.
If this is unavoidable, you can create one "master" init() that explicitly controls the order of the other, "child" init() functions.
An example of a "wizard" init() that manages other initialization functions:
func init() { initA() initB() } func initA() {} func initB() {}
In the above example, initA() will always work until initB() .
Relevant section from the specification: Initialization of the package .
See also the related question: What does the lexical order of file names mean?
source share