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?

  • And clarification is possible, why 'FirstAnswer ()' will be called before 'init ()' - softland

1 answer 1

The init() function is always executed.

Example ( playground ):

 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: enter image description here

If you have questions, ask.

  • Everything is very clear, thanks. You can recommend some go textbook, otherwise I am just starting and everything is not very clear. Thanks again. - user303063
  • one
    @Jonny for starters try this book - user192664