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

Posted nyist-xsk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了map赋值前要先初始化:assignment to entry in nil map相关的知识,希望对你有一定的参考价值。

注意这种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的主要内容,如果未能解决你的问题,请参考以下文章

排坑记录ids for this class must be manually assigned before calling save():

Delphi中赋值(:=)与分配(Assign)有啥区别?

重构改善既有代码设计--重构手法07:Remove Assignments to Parameters (移除对参数的赋值)

can't assign to struct fileds in map

python中赋值问题can't assign to literal?

Cannot assign to 'self' outside of a method in the init family