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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.