第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

為什么在 init() 中檢查 nil

為什么在 init() 中檢查 nil

Go
明月笑刀無(wú)情 2021-11-01 14:13:55
我正在閱讀這篇文章,該文章在其示例中提供了此代碼:var templates map[string]*template.Template// Load templates on program initialisationfunc init() {    if templates == nil {        templates = make(map[string]*template.Template)    }為什么要檢查if templates == nil的init()?在執(zhí)行的這一點(diǎn)上它不會(huì)總是相同的嗎?
查看完整描述

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初始化的位置。


查看完整回答
反對(duì) 回復(fù) 2021-11-01
?
MMMHUHU

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ò)誤。防御性編程。


查看完整回答
反對(duì) 回復(fù) 2021-11-01
  • 2 回答
  • 0 關(guān)注
  • 190 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)