In Go, the init() function is a special, built-in function that is called automatically before the main() function runs. It is used to perform package-level initialization or setup that needs to happen before your program starts executing its main logic.


Key points about init()

  1. Automatic execution

  2. One or more per package

  3. Purpose

  4. No parameters and no return

    func init() {
        // initialization code
    }
    

Example

package main

import "fmt"

var globalVar int

func init() {
    fmt.Println("Initializing globalVar")
    globalVar = 42
}

func main() {
    fmt.Println("Main starts")
    fmt.Println("globalVar =", globalVar)
}

Output:

Initializing globalVar
Main starts
globalVar = 42

Summary