Gopher

Init function in Golang

Published on 10 May 2020
Last Updated on 10 May 2020

init function is a special function in Golang. init function does not take any arguments not does it return any value just like the main function.

A package can not contain more than one init function. init function can not be called from anywhere else in the program. init function can not be referenced by any other parts of the program.

init function is called before main function is called. init function can be used for various purposes however most go programs make use of init function to initialize global variables or to setup the environment needed for the program to work properly.

Program given below demonstrates how init function can be used.

// program to demonstrate use of init function
package main

import "fmt"

var a int

func init() {
	fmt.Println("init is called")
	a = 2
}

func main() {
	fmt.Println("main is called")
	fmt.Println("a is ", a)
}

Program output

Above program produces following output:

init is called
main is called
a is  2

Program Description

In above program init function is called before the main function is called.

As displayed in above program, init function can be used for initializing variables and values that will later be used by the main function or other parts of the program.

Above program initializes the variable a using the init function.