When and in what order is the init() function executed in Go?
Hello everyone! I just started learning Go and encountered something unclear. The documentation says that you can declare an `init()` function in packages, which runs automatically. But I can't figure out exactly when it runs and in what order if there are multiple such functions.
I have a small project with three files. In the `main` package, I defined an `init()` function that prints "main init". In another file of the same package, I declared another `init()` that increments a counter. The imported `config` package also has its own `init()` that reads settings. I expected them to execute in some logical order, but when running the program, the output was not obvious.
Here's an example code:
```go
// main.go
package main
import "fmt"
var counter int
func init()
No answers yet.
Log in to leave an answer