/ / Dlaczego warto sprawdzić nil w init () - go

Po co sprawdzać zero w init () - go

Czytam Ten artykuł który oferuje ten kod w swoim przykładzie:

var templates map[string]*template.Template

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

Po co sprawdzać if templates == nil w init()? Wygrał „zawsze będzie tak samo w tym momencie w wykonaniu?

Odpowiedzi:

6 dla odpowiedzi № 1

Nie ma powodu, aby sprawdzać zero w kodzie podanym w artykule. Istnieją inne sposoby strukturyzacji kodu.

Opcja 1:

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

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

Opcja 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
}

Opcja 3:

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

Zobaczysz wszystkie te podejścia w kodzie Go. Wolę drugą opcję, ponieważ to wyjaśnia templates jest inicjowany w funkcji initTemplates. Inne opcje wymagają rozejrzenia się, aby dowiedzieć się, gdzie templates jest zainicjowany.


1 dla odpowiedzi nr 2

Specyfikacja języka Go Programming

Inicjalizacja pakietu

Zmienne można również inicjować za pomocą nazwanych funkcji init zadeklarowany w bloku pakietu, bez argumentów i bez wyniku parametry.

func init() { … }

Można zdefiniować wiele takich funkcji, nawet w obrębie jednego źródła plik.

Teraz lub w przyszłości może być wiele init funkcje w pakiecie. Na przykład,

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
}

Programy powinny mieć zero błędów. Programuj defensywnie.