I have a simple main.go
file as follows:
package main
import "fmt"
func init() {
fmt.Println("init!")
}
func main() {
// init()
fmt.Println("main")
}
When I run this program I see the following output!
init
main
I'm getting totally confused! I guess both functions with func()
signature get run as entry points. But, more interestingly, I can't make a call to init
function in main
!
Can anyone please explain me what's wrong with this code?
init
is a special name for a function that initializes a package. It's called automatically, and the spec mentions "init functions cannot be referred to from anywhere in a program". You should use any other name.