Go language reserves main() and init() function for special purposes which can help simplify your code in Golang.
main()
main() is a special type of function that can be defined in a package and it acts as an entry point for the executable program.
Things to note about main() function
- It doesn't take any arguments and does not return anything
- Go calls the main() function automatically
- Executable programs must have a single main package and main() function defined
package main
import "fmt"
func main() {
fmt.Println("Starting main function!")
fmt.Println("Main function is called automatically")
}
init()
init() function can be defined in any package and there can be multiple init() functions as well.
Things to note about init() function
- It does not take any arguments and does not return anything
- There can be multiple init() functions and they are executed in the order they are created
- init() function is called before the main() function
- init() function from multiple files are executed, they are executed in lexical order of the file names
Go code follows these four steps when deciding the order of the init() function
- Import the package and initialize the package
- Initialize the constant variables in the file
- Initialize the variables in the file
- Execute the init() function in the file
Order - import >> const >> var >> init()
Let's look at an example to get understand the flow of the code. We can create two files. First is the main.go
file which defines the main package.
Then we can create firstpkg.go
to define a package which will be used in the main package
Scenario
Firstpkg
package has one global variable that will be initialized at the start. Then we have 3 init() functions which will run and then we need to use the global variable of this package in the main package.
Contents from main.go
package main
import (
"fmt"
"play.ground/firstpkg"
)
func init() {
fmt.Println("Init from main package")
fmt.Println(firstpkg.GetGlobalValue())
}
func main() {
firstpkg.Run()
}
Contents from firstpkg.go
package firstpkg
import "fmt"
var myVar = getMyVarValue()
func getMyVarValue() string {
fmt.Println("Inside getMyVarValue()")
return "awesome"
}
func init() {
fmt.Println("Init from firstpkg 1")
}
func init() {
fmt.Println("Init from firstpkg 2")
}
func init() {
fmt.Println("Init from firstpkg 3")
}
func GetGlobalValue() string {
return myVar
}
func Run() {
fmt.Println("Run!!!")
}
Output:
Inside getMyVarValue()
Init from firstpkg 1
Init from firstpkg 2
Init from firstpkg 3
Init from main package
awesome
Run!!!
Execution Order
- Initialize the
firstpkg
package- Initialize the
myVar
variable - Running the init() functions based on how they are defined (1, 2, 3)
- Initialize the
- init() function of the
main
package - main() function of the
main
package - Run() function of the
firstpkg
package
Summary
Join our discord channel for more questions and discussion
Discord - https://discord.gg/AUjrcK6eep
Top comments (0)