What are init functions in Go?

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")
}

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)
}

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.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved