Go🔧Core Languagebeginner
init Functions
Go · Core Language · Run with go run
Explanation
`init` is a special function that runs automatically before `main`, after all package-level variables are initialized. A package (or even a single file) may declare multiple `init` functions; they run in the order they appear. `init` takes no arguments and returns nothing — it cannot be called directly.
Real-World Scenario
A database driver package registers itself with `database/sql` in an `init` function. Importing the driver for its side effect (`import _ "github.com/lib/pq"`) triggers `init`, which calls `sql.Register` — the program never references the package by name.
Quick Snippet
snippet.go
var config map[string]string
func init() {
// Runs once, before main, after package vars are set
config = map[string]string{
"env": "production",
"tier": "backend",
}
}
func main() {
fmt.Println(config["env"]) // production — already populated
}Full Example
init_functions.go
// Compile: go run init_functions.go
// Output:
// first init ran
// second init ran
// main: env=production
package main
import "fmt"
var config map[string]string
// Multiple init functions run in source order, before main.
func init() {
fmt.Println("first init ran")
config = map[string]string{"env": "production"}
}
func init() {
fmt.Println("second init ran")
}
func main() {
fmt.Println("main: env=" + config["env"])
}
Run command
go run init_functions.go