Go:分配给 nil 映射中的条目

Go : assignment to entry in nil map

在下面的代码中尝试将值设置为 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,
       ]

请帮我修正错误。

The Go Programming Language Specification

Map types

A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:

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

The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.

你写:

var countedData map[string][]ChartElement

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

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

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

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

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