Search⌘ K
AI Features

Puzzle 21 Explanation: init Is Special

Explore how the init function works uniquely in Go, allowing multiple definitions per package and serving as the final stage of package initialization. Understand best practices for using init, including why it should be reserved for special cases and considerations around error handling and package-level variables.

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 ...