0
0
GoConceptBeginner · 3 min read

What is init function in Go: Explanation and Example

In Go, the init function is a special function that runs automatically before the main program starts. It is used to set up or initialize things like variables or configurations without being called explicitly.
⚙️

How It Works

The init function in Go is like a setup helper that runs by itself before your program's main code begins. Imagine you are preparing ingredients before cooking a meal; the init function prepares everything needed so the main cooking (your program) can run smoothly.

Every Go package can have one or more init functions. When you run your program, Go automatically calls all these init functions in the order of package dependencies, before the main function starts. You never call init yourself; Go does it for you.

💻

Example

This example shows how the init function sets up a variable before the main function uses it.

go
package main

import "fmt"

var message string

func init() {
    message = "Hello from init!"
}

func main() {
    fmt.Println(message)
}
Output
Hello from init!
🎯

When to Use

Use the init function when you need to prepare or configure something before your program runs. For example, you can use it to:

  • Initialize package-level variables
  • Set up connections like databases or files
  • Register types or plugins automatically

This helps keep your main function clean and focused on the main logic.

Key Points

  • The init function runs automatically before main.
  • You cannot call init manually.
  • Each package can have multiple init functions.
  • Use init to set up initial state or configuration.

Key Takeaways

The init function runs automatically before the main function starts.
Use init to prepare variables or setup needed before your program runs.
You never call init yourself; Go calls it for you.
Multiple init functions can exist in one package and run in order.
Init helps keep main clean by handling setup tasks separately.