为什么要在init()中检查nil

I'm reading this article which offers this code in its example:

var templates map[string]*template.Template

// Load templates on program initialisation
func init() {
    if templates == nil {
        templates = make(map[string]*template.Template)
    }

Why check for if templates == nil in init()? Won't it always be the same at this point in execution?

There is no reason to check for nil in the code provided in the article. There are other ways to structure the code.

Option 1:

var templates = map[string]*template.Template{}

func init() {
    // code following the if statement from the function in the article
}

Option 2:

var templates = initTemplates()

func initTemplates() map[string]*template.Template{} {
    templates := map[string]*template.Template{}
    // code following the if statement from the function in the article
    return templates
}

Option 3:

func init() {
    templates = make(map[string]*template.Template)
    // code following the if statement from the function in the article
}

You will see all of these approaches in Go code. I prefer the second option because it makes it clear that templates is initialized in the function initTemplates. The other options require some looking around to find out where templates is initialized.

The Go Programming Language Specification

Package initialization

Variables may also be initialized using functions named init declared in the package block, with no arguments and no result parameters.

func init() { … }

Multiple such functions may be defined, even within a single source file.

Now or in the future there may be multiple init functions in the package. For example,

package plates

import "text/template"

var templates map[string]*template.Template

// Load project templates on program initialisation
func init() {
    if templates == nil {
        templates = make(map[string]*template.Template)
    }
    // Load project templates
}

// Load program templates on program initialisation
func init() {
    if templates == nil {
        templates = make(map[string]*template.Template)
    }
    // Load program templates
}

Programs should have zero bugs. Program defensively.