Golang / GoLang Basics Interview Questions
What is the init() function and when does it run?
init() is an optional special function that runs automatically after all package-level variable initialisations — before main(). It takes no arguments, returns nothing, and cannot be called directly. A single file may contain multiple init() functions.
package main import ( "fmt" _ "github.com/lib/pq" // blank import: run pq's init() for side effects ) // registers the postgres driver var cfg *Config func init() { // Runs BEFORE main(), AFTER package-level vars are initialised var err error cfg, err = loadConfig("app.yaml") if err != nil { panic(fmt.Sprintf("config init failed: %v", err)) } fmt.Println("config loaded") } func main() { fmt.Println("main running") // cfg is guaranteed to be non-nil here } // INITIALISATION ORDER within a package: // 1. Package-level variables (in dependency order) // 2. init() functions (in source file order, multiple per file allowed) // 3. main() â only in package main // Across packages: imported packages initialise first // Go guarantees no circular init dependencies
More Related questions...