Init function in modules

A Go package can have an init function. This function is called at the time when the package is imported. You can put in any initialization you want here. e.g.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

func init() {
    fmt.Print("Hello")
}

func init() {
    fmt.Print(" World")
}

func main() {
    fmt.Println(" People")
}

The above will print out Hello World People.

The init function can be repeated as many times as we want and they will be executed in the order listed. This also means that if package A imports package B, the init functions of B will happen before any init function of A get executed.

The init function is niladic i.e. it takes no args and returns nothing.

Sometimes we want to import a package only to run it’s init function i.e. we only want the side-effects of initialization. e.g.

1
2
3
4
5
import (
  "image/jpeg"
  _ "image/png"
  _ "image/gif"
)

In the above snippet, we imported image/png only for it’s initialization function i.e. prior registration of a decoder function.

If you want to see a real world example (there are many), here is one from Cobra - A Commander for modern Go CLI interactions