I can not understand how exactly the function init() in golang .
Is it always executed or only when there is a main() function? And how does the execution occur when I have several plug-in packages?
I can not understand how exactly the function init() in golang .
Is it always executed or only when there is a main() function? And how does the execution occur when I have several plug-in packages?
The init() function is always executed.
var finalAnswer = FirstAnswer() func FirstAnswer() int { return 1 } func init() { finalAnswer = 0 } func main() { if finalAnswer == 0 { fmt.Println("Значение finalAnswer было изменено на 0 в init функции") } } The FirstAnswer() function is guaranteed to be executed before init() , while the init() function is guaranteed to be executed before main() .
If you have several packages, the init() function will be executed for each and only in the order in which they are connected.
Sometimes it happens that you don't have a main() function, but you have init() . This is absolutely normal, because sometimes you need to do some kind of short calculation, load a file, or initialize several variables.
For more visibility of the work of init() for several packages, use the image below: 
If you have questions, ask.
Source: https://ru.stackoverflow.com/questions/885704/
All Articles