The init function in Golang

The init function is a powerful function in Go. It allows doing things like initialization of a package that otherwise really hard to achieve. In this post, we are going to take a look at Go’s init function.

What is the init function in Golang?

The init function is a function that takes no argument and returns nothing. This function executes after the package is imported and maintains the order of execution. That means multiple init functions can be defined in a file and they will be called one after another maintaining the order.

How to use the init function in Go?

The init function in Go should be used to do the tasks we want to do before doing all other things in that file. That means it is more suited to tasks like initializations.

package main

import (
	"fmt"
)

func init() {
	fmt.Println("Runs first")
}

func main() {
	fmt.Println("Hello, World")
	
	// Runs first
	// Hello, World
}

Order of the init functions

The order of the init functions matter. The way they are declared in the same order they are executed. Here is an example showing how that works.

package main

import (
	"fmt"
)

func init() {
	fmt.Println("Runs first")
}

func init() {
	fmt.Println("Runs second")
}

func main() {
	fmt.Println("Hello, World")
	
	// output:
	// Runs first
	// Runs second
	// Runs last
	// Hello, World
	
}

func init() {
	fmt.Println("Runs last")
}

Observe that even though one of the init function has been declared after the main, it still runs before main and maintains the order.

Why is init useful?

The init functions are extremely useful due to the fact that they are executed immediately before any other functions from the package and they maintain the order of declaration and execute in the same order. This helps create programs that maintain a steady flow of execution.

Further Read: Go Sleep Function