Skip to content

Go Init Functions

The init function is a special function in Go that runs automatically before the main function or any other code in the package is executed.

1. Basic Usage

You don't call init() yourself. Go calls it for you.

package main

import "fmt"

func init() {
    fmt.Println("Init: Running before main")
}

func main() {
    fmt.Println("Main: Starting now")
}

2. Execution Order

  1. Variables: All package-level variables are initialized first.
  2. init() functions: Then, all init() functions are called.
  3. main() function: Finally, the main() function is called.

3. Multiple Init Functions

You can have multiple init() functions in the same file or across multiple files in the same package. They will run in the order they appear.

1
2
3
4
5
6
7
func init() {
    fmt.Println("First init")
}

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

Why use init()?

  • Variable setup: Initializing complex global variables that can't be set with a simple assignment.
  • Environment check: Checking if necessary environment variables or configuration files are present.
  • Registration: Registering drivers (e.g., database drivers) or plugins.

Best Practices

  • Keep it simple: Don't put heavy logic or long-running tasks in init. It can make your program hard to test and slow to start.
  • Avoid side-effects: Try to keep init functions focused only on setting up the internal state of the package.