1. 程式人生 > >map賦值前要先初始化:assignment to entry in nil map

map賦值前要先初始化:assignment to entry in nil map

註意 blog pre article csdn href net led tps

註意這種map的嵌套的形式,make只初始化了map[string]T部分(T為map[int]int),所以下面的賦值會出現錯誤:

test := make(map[string]map[int]int)
test["go"][0] = 0 // error
1
2
正確的做法:

test := make(map[string]map[int]int)
test["go"] = make(map[int]int)
test["go"][0] = 0
1
2
3
一個常用的做法:

test := make(map[string]map[int]int)
if test["go"] = nil {
    test["go"] = make(map[int]int)
}
test["go"][0] = 0
原文:https://blog.csdn.net/jason_cuijiahui/article/details/79410471

map賦值前要先初始化:assignment to entry in nil map