1 回答

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果您打算存儲(chǔ)值類型的零值,則不一樣。
看這個(gè)例子:
m := map[string]string{
"empty": "",
}
if v, ok := m["empty"]; ok {
fmt.Printf("'empty' is present: %q\n", v)
} else {
fmt.Println("'empty' is not present")
}
if v, ok := m["missing"]; ok {
fmt.Printf("'missing' is present: %q\n", v)
} else {
fmt.Printf("'missing' is not present")
}
它輸出(在Go Playground上嘗試):
'empty' is present: ""
'missing' is not present
確實(shí),如果您從不在地圖中存儲(chǔ)零值,您可以簡(jiǎn)單地使用if m[value] == zeroValue {}.
可以利用地圖的這種“屬性”來優(yōu)雅地創(chuàng)建集合。
并且使用這種“技術(shù)”還有另一個(gè)優(yōu)點(diǎn):您可以以緊湊的方式檢查多個(gè)鍵的存在(您不能使用特殊的“comma ok”形式來做到這一點(diǎn))。
- 1 回答
- 0 關(guān)注
- 110 瀏覽
添加回答
舉報(bào)