DEV Community

Cover image for 🐹 Go’s init() Function
Sajjad Rahman
Sajjad Rahman

Posted on

🐹 Go’s init() Function

Sometimes, we want some basic things to be done before we start our real work. Take a real-life example: the school bell. We don’t ring the bell ourselves, but when the bell rings, we all go to class and start the lessons.

1. Basics of init()

  • init() is a special function in Go.
  • It runs automatically before main() function.
  • You don’t call it. Go calls it for you.

2. Examples

package main
import "fmt"

func init() {
    fmt.Println("I run before main()")
}

func main() {
    fmt.Println("I am the main function")
}
Enter fullscreen mode Exit fullscreen mode

Output:

I run before main()
I am the main function
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • init() ran first.
  • Then main() started.

Another example with variables:

package main
import "fmt"

var a = 10

func init() {
    fmt.Println("Before change, a =", a)
    a = 20
    fmt.Println("After change, a =", a)
}

func main() {
    fmt.Println("Inside main, a =", a)
}
Enter fullscreen mode Exit fullscreen mode

Output:

Before change, a = 10
After change, a = 20
Inside main, a = 20
Enter fullscreen mode Exit fullscreen mode

Here, init() changed the variable before main() used it.

3. Multiple init() Functions

  • we can write more than one init() in the same file.
  • we can write them in many files.
  • we can even have init() in imported packages.

Example:

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

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

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

Output:

First init
Second init
Main runs
Enter fullscreen mode Exit fullscreen mode

👉 Like multiple bells before class:

  • First bell (init()) → Get ready
  • Second bell (init()) → Take your seats
  • Teacher (main()) → Starts the lesson

4. Execution Order

Go always follows the same order:

Package variables → init() → main()
Enter fullscreen mode Exit fullscreen mode

Example:

var x = setValue()

func setValue() int {
    fmt.Println("setValue() called")
    return 10
}

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

func main() {
    fmt.Println("Inside main()")
}
Enter fullscreen mode Exit fullscreen mode

Output:

setValue() called
Inside init()
Inside main()
Enter fullscreen mode Exit fullscreen mode

Variables are prepared first, then init(), then main().

5. Advanced Analysis

  • ✅ You can write many init() functions.
  • ⚠️ But don’t overuse them—it makes code hard to read.
  • ✅ Variable initialization happens before init().
  • ✅ Imported packages run their init() before your main package’s init().

  • ❌ You can call init() manually, but that’s bad practice.

👉 Think: If the school peon rings the bell twice manually, everyone gets confused 😵. That’s why Go rings it automatically.

6. Real-Life Example

Imagine your app needs a database connection. Instead of setting it up inside main(), you can prepare it in init().

package config
import "fmt"

var DBConnection string

func init() {
    fmt.Println("Setting up database connection...")
    DBConnection = "mysql://user:password@localhost:3306/mydb"
}
Enter fullscreen mode Exit fullscreen mode
package main
import (
    "fmt"
    "config"
)

func main() {
    fmt.Println("Main function running")
    fmt.Println("Using DB:", config.DBConnection)
}
Enter fullscreen mode Exit fullscreen mode

Output:

Setting up database connection...
Main function running
Using DB: mysql://user:password@localhost:3306/mydb
Enter fullscreen mode Exit fullscreen mode

👉 Just like the stage crew sets up the stage 🎤 before the actors arrive, init() prepares the program.

7. Best Practices

✅ Good uses of init()

  • Load configurations (database, environment)
  • Initialize variables
  • Register routes, plugins, or commands

❌ Bad uses of init()

  • Don’t put your main logic here
  • Don’t overuse it
  • Don’t call it yourself

Rule: Keep init() short, clean, and only for preparation.

✅ Order of execution:

Variables → init() → main()
Enter fullscreen mode Exit fullscreen mode

✅ You can have unlimited init() functions (but keep it minimal).
✅ Imported packages run their init() first.
❌ Don’t call init() yourself.

Think of init() as the backstage crew that prepares the play before the actors come on stage.

Thank You For Your Reading

Top comments (0)