The GO language has a very good way to handle module / package initialization.
There is a description of this boot problem at link
For simplicity see this example showing implicit and explicit execution in GO Language
Source: main.go
package main
import (
"fmt"
cmds "./commands"
initialization "./init"
)
var isInitialized = initialization.IsApplicationInitialized()
func main() {
fmt.Printf("•• Invocando o método main\n")
initialization.Configure()
// Inicializando a Configuração para os Comandos
cmds.InitializeCmdConfig()
}
Source: init / init.go
package init
import "fmt"
func IsApplicationInitialized() bool {
fmt.Printf("•• Invocando o método IsApplicationInitialized\n")
return true
}
func init() {
fmt.Printf("•• Invocando o método init de init.go no package init\n")
}
func Configure() {
fmt.Printf("•• Invocando o método Configure de init.go no package init\n")
}
Execution Result:
•• Invocando o método init de init.go no package init
•• Invocando o método init de whatever.go no pacote commands
•• Invocando o método IsApplicationInitialized no package init
•• Invocando o método init em main.go
•• Invocando o método main
•• Invocando o método Configure de init.go no package init
•• Invocando o método InitializeCmdConfig de whatever.go no pacote commands
Below is an explanation.
We can think of the init method as being similar to a static block in a Java class (in this case executed in the class load process by the JVM) but we can not assume anything in relation to the implicit order. The above result was obtained in version 1.4.2 of the GO on Mac OSX but can not guarantee if it will be the same in other versions. You can only guarantee what is documented.
In this example, the GO runtime guarantees that the IsApplicationInitialized()
method will run before the init()
method exists in main.go
and that this init()
method will be executed before the main()
method in the same source. >
The init()
method is always called on a given packet regardless of whether it exists or
not a main
, so if we do the import
of a package that has a method init
this method will be executed, but always after those methods referenced in global scope variable declarations. We can also have multiple init()
methods in a given package and they are executed, as has already been emphasized, after variables are initialized.
It's healthy for the programmer to make no assumptions about order
these methods to be performed. In case you need a pre-defined order use the technique shown above when initializing a variable with the call of a
method: var isInitialized = initialization.IsApplicationInitialized()
. This will force the execution order of a given code before any method init
of that package.
Use init
methods to initialize tables of values for a given API, for example. See an example of using the init()
method in the font line 480 bzip2 .go