Go:分配到nil map中的条目

Alt*_*ion 4 runtime-error go goroutine

我现在比较新,我在这个网站上搜索了这个问题,并且回答了问题,但是无法对我的案例实施这些答案.我有一个代码:

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
}
Run Code Online (Sandbox Code Playgroud)

这种方法之外的结构没有麻烦.也map不会执行(如测试恐慌这里).我知道麻烦在于将数据递增到结构中.

有一些goroutines,正在向通道发送数据,countedData方法rgabs all,应该像这样制作一个地图:

map =>
    "typeOne" => 
       [
         ChartElement,
         ChartElement,
         ChartElement,
       ],
    "typeTwo" => 
       [
         ChartElement,
         ChartElement,
         ChartElement,
       ]
Run Code Online (Sandbox Code Playgroud)

如何以正确的方式实现这种插入?

pet*_*rSO 25

Go编程语言规范

地图类型

使用内置函数make创建一个新的空映射值,它将map类型和可选容量提示作为参数:

make(map[string]int)
make(map[string]int, 100)
Run Code Online (Sandbox Code Playgroud)

初始容量不限制其大小:映射增长以容纳存储在其中的项目数,但nil映射除外.零地图等同于空地图,但不能添加任何元素.

你写:

var countedData map[string][]ChartElement
Run Code Online (Sandbox Code Playgroud)

相反,要初始化地图,写,

countedData := make(map[string][]ChartElement)
Run Code Online (Sandbox Code Playgroud)