An init function is a parameterless, resultless Go function that initializes package state automatically. Package variables and constants are evaluated first, followed by init functions and then main. section 2.3.1
Avoid the common mistake of treating init as an ordinary callable function:
- Initialize imported packages before the importing package; a dependency such as redis runs its init before main's init. section 2.3.1
- Allow multiple init functions in one package or source file, but do not rely on their order across files because renaming files can change it. section 2.3.1
- Use a blank import such as _ "foo" when package initialization is needed for side effects without directly using its exported API. section 2.3.1
- Do not call init directly; it is reserved for automatic package initialization and produces a compilation error when invoked. section 2.3.1
Replace connection setup with caller-controlled initialization
Opening a database and storing it globally inside init forces failures to panic, creates the connection before every test, and lets package code control application-wide state. A createClient function instead returns either the connection or an error, allowing callers to retry, fall back, or choose when setup occurs. section 2.3.2
package main
import "fmt"
var a = func() int {
fmt.Println("var") #1
return 0
}()
func init() {
fmt.Println("init") #2
}
func main() {
fmt.Println("main") #3
}
Trace the observable order from package-level variable initialization through init and finally main. section 2.3.1

