2 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
沒(méi)有理由在文章提供的代碼中檢查 nil。還有其他方法可以構(gòu)建代碼。
選項(xiàng)1:
var templates = map[string]*template.Template{}
func init() {
// code following the if statement from the function in the article
}
選項(xiàng) 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
}
選項(xiàng) 3:
func init() {
templates = make(map[string]*template.Template)
// code following the if statement from the function in the article
}
您將在 Go 代碼中看到所有這些方法。我更喜歡第二個(gè)選項(xiàng),因?yàn)樗宄乇砻鱰emplates是在函數(shù)中初始化的initTemplates。其他選項(xiàng)需要環(huán)顧四周以找出templates初始化的位置。

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
變量也可以使用init 在包塊中聲明的函數(shù)進(jìn)行初始化,沒(méi)有參數(shù)和結(jié)果參數(shù)。
func init() { … }
即使在單個(gè)源文件中,也可以定義多個(gè)這樣的函數(shù)。
現(xiàn)在或?qū)?lái)可能會(huì)有多個(gè)init功能包。例如,
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
}
程序應(yīng)該有零錯(cuò)誤。防御性編程。
- 2 回答
- 0 關(guān)注
- 190 瀏覽
添加回答
舉報(bào)