在下面的代码中尝试将值设置为map( countedData) 时,我收到一个错误消息,指出assignment to entry in nil map.func receiveWork(out <-chan Work) map[string][]ChartElement { var countedData map[string][]ChartElement for el := range out { countedData[el.Name] = el.Data } fmt.Println("This is never executed !!!") return countedData}Println 不执行(因为在此之前错误发生在留置权上)。有一些 goroutines 将数据发送到通道,receiveWork方法应该制作这样的地图:map => "typeOne" => [ ChartElement, ChartElement, ChartElement, ], "typeTwo" => [ ChartElement, ChartElement, ChartElement, ]请帮我修复错误。
2 回答

神不在的星期二
TA贡献1963条经验 获得超6个赞
使用内置函数 make 创建一个新的空映射值,该函数将映射类型和可选的容量提示作为参数:
make(map[string]int) make(map[string]int, 100)初始容量不限制其大小:地图增长以容纳存储在其中的项目数量,除了 nil 地图。一个 nil 映射相当于一个空映射,只是不能添加任何元素。
你写:
var countedData map[string][]ChartElement
相反,要初始化地图,请写入,
countedData := make(map[string][]ChartElement)

30秒到达战场
TA贡献1828条经验 获得超6个赞
另一种选择是使用复合文字:
countedData := map[string][]ChartElement{}
https://golang.org/ref/spec#Composite_literals
- 2 回答
- 0 关注
- 200 浏览
添加回答
举报
0/150
提交
取消