main and init function in Golang (original) (raw)
Last Updated : 22 Aug, 2024
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:
C `
// 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:
C `
// 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