package main
func init() {
fmt.Println("This will get called on main initialization")
}
func main() {
fmt.Println("My Wonderful Go Program")
}
$ go run main.go
This will get called on main initialization
My Wonderful Go Program
package main
import "fmt"
var name string
func init() {
fmt.Println("This will get called on main initialization")
name = "Elliot"
}
func main() {
fmt.Println("My Wonderful Go Program")
fmt.Printf("Name: %s\n", name)
}
$ go run main.go
This will get called on main initialization
My Wonderful Go Program Name: Elliot
Note - It’s incredibly important to note that you cannot rely upon the order of execution of your init() functions. It’s instead better to focus on writing your systems in such a way that the order does not matter.
Note - A more in-depth overview of the order of initialization in Go can be found in the official docs: Package Initialization
var WhatIsThe = AnswerToLife()
func AnswerToLife() int {
return 42
}
func init() {
WhatIsThe = 0
}
func main() {
if WhatIsThe == 0 {
fmt.Println("It's all a lie.")
}
}
package main
import "fmt"
// this variable is initialized first due to
// order of declaration
var initCounter int
func init() {
fmt.Println("Called First in Order of Declaration")
initCounter++
}
func init() {
fmt.Println("Called second in order of declaration")
initCounter++
}
func main() {
fmt.Println("Does nothing of any significance")
fmt.Printf("Init Counter: %d\n", initCounter)
}
$ go run test.go
Called First in Order of Declaration
Called second in order of declaration
Does nothing of any significance
Init Counter: 2
Originally published on https://tutorialedge.net/golang/the-go-init-function/
Write your response...
Never miss a post from Prasad Patil, when you sign up for Ednsquare.