init Functions Run Before main

Multiple init functions in one file execute top to bottom after imports load, so config setup and connection warming finish before main starts.

GoConfig Management

Code

snippet
package main

import "fmt"

var connected bool

// 同一文件允许多个 init:按声明顺序在 main 之前执行
func init() {
	connected = true
	fmt.Println("init 1: config loaded")
}

func init() {
	fmt.Println("init 2: pool warmed, connected =", connected)
}

// main 一定在所有 init 之后运行:此时全局状态已就绪
func main() {
	fmt.Println("main starts")
	fmt.Println("connected =", connected)
}

The code in one pass

Structurally, expect the functions init and main and nothing else.

Caveats

  • All standard library — copy it in and it runs.

Putting it to use

Entry signature: func init()

Look for the init 1: config loaded, init 2: pool warmed, connected =, main starts prefixes as the file runs; each tag names the step that printed it.

Core lines

func init() {
	connected = true
	fmt.Println("init 1: config loaded")
}
func init() {
	fmt.Println("init 2: pool warmed, connected =", connected)
}
func main() {
	fmt.Println("main starts")
	fmt.Println("connected =", connected)
}

Interactive Tools for This Topic

FAQ

What does init Functions Run Before main print when run?
The script runs standalone; its 4 labeled outputs include `init 1: config loaded`, `init 2: pool warmed, connected =`, `main starts`.