Go language reserves main() and init() function for special purposes which can help simplify your code in Golang.
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
package main
import "fmt"
func main() {
fmt.Println("Starting main function!")
fmt.Println("Main function is called automatically")
}
init() function can be defined in any package and there can be multiple init() functions as well.
Things to note about init() function
Go code follows these four steps when deciding the order of the init() function
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
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!!!")
}
Inside getMyVarValue()
Init from firstpkg 1
Init from firstpkg 2
Init from firstpkg 3
Init from main package
awesome
Run!!!
firstpkg
package
myVar
variablemain
packagemain
packagefirstpkg
packageJoin our discord channel for more questions and discussion
Discord - https://discord.gg/AUjrcK6eep
We will reach out when exciting new posts are available. We won’t send you spam. Unsubscribe at any time.