【问题标题】:Go : assignment to entry in nil mapGo : 分配给 nil 映射中的条目
【发布时间】:2016-02-13 11:40:07
【问题描述】:

当尝试在下面的代码中为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 不执行(因为错误发生在之前的留置权上)。

有一些 goroutine 正在向通道发送数据,receiveWork 方法应该像这样制作地图:

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

请帮我修复错误。

【问题讨论】:

  • 看起来您的频道传递到receiveWork 永远不会关闭。您需要确保它关闭才能结束 for 循环。
  • 它结束了,在 main 函数中,当所有 goroutines 完成他们的工作,并且写入到 out 通道完成。

标签: go runtime-error goroutine


【解决方案1】:

The Go Programming Language Specification

Map types

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

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

初始容量不限制其大小:地图会增长以适应 存储在其中的项目数,nil 地图除外。一种 nil map 等价于一个空 map,除了没有元素可以是 已添加。

你写:

var countedData map[string][]ChartElement

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-31
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多