← Back to Go Course | Chapter 10: Packages & Modules | Lesson 5 of 6

The init() Function

init() is a package's own 'before anything else happens' checklist that Go automatically runs the moment the package is loaded, without you ever calling it yourself.

Defining init()

A function named init with no parameters or return values runs automatically as soon as its package is initialized, before the program's main() function begins -- you never call it explicitly yourself.

Example: Defining init()

markup
package main

import "fmt"

func init() {
	fmt.Println("init runs first")
}

func main() {
	fmt.Println("main runs second")
}

Multiple init() Functions

A single package can contain multiple init() functions, even several within one file, and Go runs all of them in the order they appear (across files, in filename order) before main starts.

Example: Multiple init() Functions

markup
package main

import "fmt"

func init() {
	fmt.Println("first init")
}

func init() {
	fmt.Println("second init")
}

func main() {
	fmt.Println("main")
}

Common Uses for init()

init() is typically used for one-time setup that must happen before any other code runs, like validating required configuration or registering something with a shared registry, since it's guaranteed to run before main.

Note: Prefer an explicit setup function over init() when the initialization order or parameters genuinely matter to callers.

Example: Common Uses for init()

markup
package main

import "fmt"

var validConfig bool

func init() {
	validConfig = true // pretend this checked real configuration
}

func main() {
	fmt.Println("config valid:", validConfig)
}
Common Mistakes
  1. Relying on a specific execution order across multiple init() functions in different files without understanding Go's file-name-based ordering rules within a package.
  2. Using init() for complex application logic that would be clearer as an explicit, callable setup function.
  3. Forgetting a package can have multiple init() functions (even multiple per file), all of which run automatically.
Chapter Summary
  • func init() runs automatically when a package is loaded, before main() starts.
  • A package can define multiple init() functions, even several in the same file.
  • init() takes no arguments and returns no values -- it can't be called explicitly.
  • It's commonly used for one-time setup like registering drivers or validating configuration.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.