I've tried to find a precise explanation of what the init()
function does in Go. I read what Effective Go says but I was unsure if I understood fully what it said. The exact sentence I am unsure is the following:
And finally means finally: 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.
What does all the variable declarations in the package have evaluated their initializers
mean? Does it mean if you declare "global" variables in a package and its files, init() will not run until all of it is evaluated and then it will run all the init function and then main() when ./main_file_name is ran?
I also read Mark Summerfield's go book the following:
If a package has one or more init() functions they are automatically executed before the main package's main() function is called.
In my understanding, init()
is only relevant when you run intend to run main() right? or the Main package. Anyone understands more precisely init()
feel free to correct me
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…