2 回答

TA貢獻1816條經驗 獲得超6個贊
在 Go 1 之前有一段時間使用不存在的鍵索引地圖導致應用程序崩潰。這已更改為返回地圖值類型的零值。這是一個設計決策,它允許(有限地)使用未初始化的語言結構而無需額外檢查,從而簡化了代碼。
例如,你可以for range遍歷nil切片和nil映射,你可以檢查它們的長度等。結果當然是一樣的:遍歷切片nil或映射將導致零次迭代,切片和映射的長度nil為 0,但你不這樣做需要if事先使用語句來判斷該值是否為非nil(以便判斷您是否可以對它們進行范圍或索引)。
當不存在的鍵的零值有用時,PeterSO 已經展示了一個很好的例子:計數器。
另一個著名的例子是將地圖用作集合。如果選擇值類型為bool,則不必初始化不在集合中的值。索引映射會告訴您值(鍵)是否在集合中,如果不在,則booltype being的零值false會告訴您它不在集合中。
例如:
fruits := map[string]bool{}
// Add elements to the set:
fruits["apple"] = true
fruits["banana"] = true
// Test if elements are in the map:
fmt.Println("Is apple in the set?", fruits["apple"])
fmt.Println("Is banana in the set?", fruits["banana"])
fmt.Println("Is plum in the set?", fruits["plum"])
fmt.Println("Is lemon in the set?", fruits["lemon"])
輸出(在Go Playground上嘗試):
Is apple in the set? true
Is banana in the set? true
Is plum in the set? false
Is lemon in the set? false

TA貢獻1725條經驗 獲得超8個贊
Go 不會引發錯誤。Go 報告錯誤。
地圖元素零值的常見用法:
package main
import (
"fmt"
)
func main() {
counts := map[string]int{}
fmt.Println(counts)
// Equivalent:
// counts["foo"] = counts["foo"] + 1
// counts["foo"] += 1
// counts["foo"]++
counts["foo"]++
fmt.Println(counts)
counts["foo"]++
fmt.Println(counts)
}
游樂場: https: //play.golang.org/p/nvHBrgV_lFU
輸出:
map[]
map[foo:1]
map[foo:2]
一個常用逗號、ok形式的map索引表達式:
package main
import (
"fmt"
)
func main() {
m := map[string]map[string]int{}
fmt.Println(m)
// panic: assignment to entry in nil map
// m["K1"]["K2"]++
_, ok := m["K1"]
if !ok {
m["K1"] = map[string]int{}
}
m["K1"]["K2"]++
fmt.Println(m)
m["K1"]["K2"]++
fmt.Println(m)
}
游樂場: https: //play.golang.org/p/9byxSSIWBre
輸出:
map[]
map[K1:map[K2:1]]
map[K1:map[K2:2]]
- 2 回答
- 0 關注
- 159 瀏覽
添加回答
舉報