Go Basic
init() in Go Programming
Order Execution of init()
When you are creating a Go Application sometimes you need to initialize some variables with their value. A way to do this thing is to call the initializer at the start of main()
function so it will initialize the variable at the start of the program or initialize a global variable. With init()
, you can run your code before the main()
function and after the initialization of global variables.
Requirement
The only thing you need is the basics of Go Programming, especially in package.
repository: https://github.com/david-yappeter/go-init-tutorial
Hands-On
init()
will be triggered before the main()
function, and follow this order of execution:
init()
will run only once.init()
will run after global variable initialization of each package and beforemain()
function.init()
will only run if the package is imported.- If there are multiple
init()
inside a file, it will be run from the top to the bottominit()
. init()
inside a package (notmain
) will be run if the package is imported.- If there are multiple
init()
across a package (exceptmain
), it will run ascending alphabetical order from the file name. - If there are multiple
init()
across multiple packages (imported), it will run from top to bottom of the imported package (order of the import). - If there are 3rd party libraries imported with
init()
inside, it follows the previous rule (order of the import).
Clone my repository and try to run it to see the log of the program.
A Package
Nested Package a.go
Nested Package f.go
Nested Package y.go
Nested Package z.go
Z Package
library nested package
library root package==========================
1st init()
==========================
global Var: 10==========================
3rd init()
==========================
global Var: 5==========================
4th init()
==========================
global Var: 100==========================
main()
==========================
globalVar: 50
So as we can see in the log.
The init()
start from package a
in this current directory then move to nested
package. In the nested
package, it will run all of the init()
alphabetical order from filename, then move to z
package, and we have a third party library with init()
function that will be runned, and init()
in the main()
package.
Downside
There are several downsides of init()
usage:
- It slows down startup time which is very often important in an era of containers and orchestration
init()
function will be executed if you import the package whenever you needed or not- Sometimes it will ruin your test. For example, if your
init()
modify some global values and it is not triggered on the test.
That’s all about init()
function in Go, hope you have a great day :).