What are the main and init functions in Go?

main() and init are two functions reserved for special purpose in Go.

The main package in the Go language contains a main function, which shows that the file is executable. The main() is the program’s entry point; we do not need to call it, and no value is passed as an argument or returned from this function.

Example

package main
import (
"fmt"
"sort"
)
func main() {
ele := []int{23,44,2,4,85}
sort.Ints(ele)
fmt.Println("Sorted elements: ", ele)
}

Explanation

  • Line 1: We create a package main.
  • Line 3–6: We import packages fmt and sort.
  • Line 9: We create a driver function main().
  • Line 11 and 12: We create a sequence and use the sort package to sort it.

The init() function is the same as the main() function in a way that no value is passed or returned from an init() function. Every package contains init() it executes when we initialize a package. It executes before the main() function and is independent of the main() function. When we cannot initialize the global variables in a global context, we use init() to initialize it. We do not need to declare the init() explicitly, and neither can we refer to it anywhere in the program, but we are allowed to create multiple init() functions; they execute in the order they are created.

Example

package main
import (
"fmt"
)
func init(){
fmt.Println("This is the init function")
}
func main() {
fmt.Println("This is the main function")
}

Explanation

  • Line 7: We create an init() function that will execute before main().
  • Line 8: This is a print statement inside the init() function.
Copyright ©2024 Educative, Inc. All rights reserved