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")
}
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

Output:

I run before main()
I am the main function
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

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)
}
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

Output:

Before change, a = 10
After change, a = 20
Inside main, a = 20
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

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")
}
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

Output:

First init
Second init
Main runs
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

πŸ‘‰ 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()
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

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()")
}
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

Output:

setValue() called
Inside init()
Inside main()
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

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"
}
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis
package main
import (
    "fmt"
    "config"
)

func main() {
    fmt.Println("Main function running")
    fmt.Println("Using DB:", config.DBConnection)
}
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

Output:

Setting up database connection...
Main function running
Using DB: mysql://user:password@localhost:3306/mydb
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

πŸ‘‰ 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()
πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis πŸ“’ Alert: sajjadrahman/gos init function lfp - Latest Analysis

βœ… 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)