DEV Community

Cover image for Understanding the init Function in Go: Purpose, Execution, and Best Practices
Md Abu Musa
Md Abu Musa

Posted on

Understanding the init Function in Go: Purpose, Execution, and Best Practices

Go init Function

In Go, the init function is a special function that is automatically executed before the main function when a package is initialized. It is primarily used for setup tasks, such as initializing global variables, opening database connections, or registering dependencies.


Key Characteristics of init Function:

  1. No Arguments & No Return Value – The init function does not take parameters or return values.
  2. Executed Automatically – It runs before main() and does not require explicit invocation.
  3. Can Have Multiple init Functions – A package can have multiple init functions, even across different files.
  4. Executed in Declaration Order – If multiple init functions exist in a package, they are executed in the order in which they appear.

Example 1: Basic init Usage

package main

import "fmt"

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

func main() {
    fmt.Println("Main function running...")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Initializing...
Main function running...
Enter fullscreen mode Exit fullscreen mode

✅ The init function runs before main().


Example 2: Using init for Global Variable Initialization

package main

import "fmt"

var config string

func init() {
    config = "Application Configured"
    fmt.Println("Configuring application...")
}

func main() {
    fmt.Println(config) // Output: Application Configured
}
Enter fullscreen mode Exit fullscreen mode

Example 3: init in Multiple Files

📌 If a package has multiple files, all init functions run before main(), in the order they appear.

File 1 (a.go)

package main

import "fmt"

func init() {
    fmt.Println("Init from a.go")
}
Enter fullscreen mode Exit fullscreen mode

File 2 (b.go)

package main

import "fmt"

func init() {
    fmt.Println("Init from b.go")
}
Enter fullscreen mode Exit fullscreen mode

Output (execution order is preserved):

Init from a.go
Init from b.go
Main function running...
Enter fullscreen mode Exit fullscreen mode

Example 4: init in a Different Package

package utils

import "fmt"

func init() {
    fmt.Println("Initializing utils package...")
}

func SayHello() {
    fmt.Println("Hello from utils!")
}
Enter fullscreen mode Exit fullscreen mode

Main File (main.go)

package main

import (
    "fmt"
    "your_project/utils"
)

func init() {
    fmt.Println("Initializing main package...")
}

func main() {
    fmt.Println("Main function running...")
    utils.SayHello()
}
Enter fullscreen mode Exit fullscreen mode

Output (Package-Level Execution Order)

Initializing utils package...
Initializing main package...
Main function running...
Hello from utils!
Enter fullscreen mode Exit fullscreen mode

✅ The init function in imported packages runs before the init function in main.


When to Use init?

Good Use Cases:

  • Initializing global variables.
  • Setting up logging configurations.
  • Registering dependencies (e.g., database connections).
  • Ensuring required setup before main() runs.

Avoid Using init for:

  • Complex logic (prefer explicit initialization in main).
  • Business logic (should be in main or other functions).

Summary

  • init() runs automatically before main().
  • It has no parameters and no return values.
  • Each package can have multiple init functions.
  • init in imported packages runs before init in main.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs