Skip to content
Related Articles

Related Articles

main and init function in Golang
  • Last Updated : 05 Sep, 2019

The Go language reserve two functions for special purpose and the functions are main() and init() function.

main() function

In Go language, the main package is a special package which is used with the programs that are executable and this package contains main() function. The main() function is a special type of function and it is the entry point of the executable programs. It does not take any argument nor return anything. Go automatically call main() function, so there is no need to call main() function explicitly and every executable program must contain single main package and main() function.

Example:




// Go program to illustrate the
// concept of main() function
  
// Declaration of the main package
package main
  
// Importing packages
import (
    "fmt"
    "sort"
    "strings"
    "time"
)
  
// Main function
func main() {
  
    // Sorting the given slice
    s := []int{345, 78, 123, 10, 76, 2, 567, 5}
    sort.Ints(s)
    fmt.Println("Sorted slice: ", s)
  
    // Finding the index
    fmt.Println("Index value: ", strings.Index("GeeksforGeeks", "ks"))
  
    // Finding the time
    fmt.Println("Time: ", time.Now().Unix())
  
}

Output:

Sorted slice:  [2 5 10 76 78 123 345 567]
Index value:  3
Time:  1257894000

init() Function

init() function is just like the main function, does not take any argument nor return anything. This function is present in every package and this function is called when the package is initialized. This function is declared implicitly, so you cannot reference it from anywhere and you are allowed to create multiple init() function in the same program and they execute in the order they are created. You are allowed to create init() function anywhere in the program and they are called in lexical file name order (Alphabetical Order). And allowed to put statements if the init() function, but always remember to init() function is executed before the main() function call, so it does not depend to main() function. The main purpose of the init() function is to initialize the global variables that cannot be initialized in the global context.



Example:




// Go program to illustrate the
// concept of init() function
  
// Declaration of the main package
package main
  
// Importing package
import "fmt"
  
// Multiple init() function
func init() {
    fmt.Println("Welcome to init() function")
}
  
func init() {
    fmt.Println("Hello! init() function")
}
  
// Main function
func main() {
    fmt.Println("Welcome to main() function")
}

Output:

Welcome to init() function
Hello! init() function
Welcome to main() function

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :