0
votes

In Go, you can define multiple init functions in a given package, all of which will be run prior to execution in unspecified order. One consequence of having multiples of such functions is that it's impossible to call or identify them in normal code. For example, the following will not compile:

func main() {
    fmt.Println(init)
}
func init() { }

(see here for a Go playground example) My question is - what advantage does being able to have multiple init functions give, and if there weren't multiple init functions, would we be able to reference or call init functions?

1

1 Answers

1
votes

Advantage of being able to have multiple init functions is IMO mainly that it improves readability by locality: You can write the initialization function next to the stuff being initialized and not remotely if you would have to centralize all the init functions to one. Which, BTW, could be then even in a different source file.

Taking a function pointer of the hypothetical per-package-single init function would be probably prohibited as well. The reason is that having such pointer would allow, in some cases, to call the init function "out of order", ie. before running its dependencies - other init functions in other packages. That would break certain guarantees.