Go:分配到nil map中的条目

时间:2016-02-13 11:40:07

标签: go runtime-error 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
}

此方法之外的结构没有问题。此外Println也没有执行(作为恐慌在这里的测试)。我知道问题在于将数据递增到结构中。

有一些goroutine正在向频道发送数据,而receiveWork方法可以创建所有内容并且应该创建这样的地图:

map =>
    "typeOne" => 
       [
         ChartElement,
         ChartElement,
         ChartElement,
       ],
    "typeTwo" => 
       [
         ChartElement,
         ChartElement,
         ChartElement,
       ]

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

2 个答案:

答案 0 :(得分:17)

  

The Go Programming Language Specification

     

Map types

     

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

make(map[string]int)
make(map[string]int, 100)
     

初始容量不限制其大小:地图增长以容纳   存储在其中的项目数,但nil地图除外。一个   nil map相当于一个空映射,除了没有元素   加入。

你写道:

var countedData map[string][]ChartElement

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

countedData := make(map[string][]ChartElement)

答案 1 :(得分:0)

另一种选择是使用复合文字:

countedData := map[string][]ChartElement{}

https://golang.org/ref/spec#Composite_literals

相关问题