Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go

What are init functions in Go?

Hunain Tahir

Overview

The init() function serves as a unique package initializer in the Go language. An init() function is package-scoped, and we can use it to set up our application state before entering into the main() function. It is invoked sequentially in a single Goroutine, along with other global variable initializations.

We can declare the init function with the init identifier.

Syntax

func init() { }

Parameters

The init function doesn’t take any arguments.

Return value

The init function doesn’t return any results.

The init identifier is not declared, so we cannot refer to it from inside the program.

Demo code

package main
import "fmt"
func init(){
  fmt.Printf("Invoked init()\n")
}

func main() {
    fmt.Printf("Executing main()\n")
}
How to invoke init function in Go

Explanation

  • The init function is invoked prior to the main function.

Defining multiple init() functions

We can define multiple init() functions in Go. We can even have multiple init functions in a single file. They’ll be invoked sequentially in the order that they appear.

package main
import "fmt"

var foo = varInit()

func varInit() string{
  fmt.Printf("initialized foo\n")
  return "foo"
}

func init(){
  fmt.Printf("First init()\n")
}

func init(){
  fmt.Printf("Second init()\n")
}

func main() {
  fmt.Printf(foo)
}
Invoking multiple init functions in GO

Explanation

  • On line 4, we initialize the global variable foo before calling the init function. The current init() will complete before the next init() is invoked.

The imported packages will get initialized before the current one. Every package is initialized only once.

The init functions defined in different files will be invoked as they are presented to the compiler. Mostly, this is in the lexical order of the file names.

RELATED TAGS

golang
go
RELATED COURSES

View all Courses

Keep Exploring