Reputation: 2170
I have a function like this:
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
I want to call it in func main()
:
func main(){
init()
}
But it does not work and told me init()
is not defined.
What's the problem?
Upvotes: 0
Views: 913
Reputation: 12256
The init
function is a special function in Golang. It is executed the first time the file is loaded, so you never have to call it directly.
From the official documentation:
Finally, each source file can define its own niladic init function to set up whatever state is required. (Actually each file can have multiple init functions.) And finally means finally: init is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.
Upvotes: 6