...

/

Puzzle 21 Explanation: init Is Special

Puzzle 21 Explanation: init Is Special

Understand how init works in Go.

We'll cover the following...

Try it yourself

Try executing the code below to see the result for yourself.

Go (1.16.5)
package main
import (
"fmt"
)
func init() {
fmt.Printf("A ")
}
func init() {
fmt.Print("B ")
}
func main() {
fmt.Println()
}

Explanation

In Go, init presents a particular case. We cannot define two functions with the same name in the same package in Go compiler. However, init is different.

Go’s documentation describes it like this: “Multiple such functions may be defined per package, ...