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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
