doujian3401 2016-06-03 18:45
浏览 27
已采纳

恐慌:分配给单个简单地图上的nil地图中的条目

I was under the impression that the assignment to entry in nil map error would only happen if we would want to assign to a double map, that is, when a map on a deeper level is trying to be assigned while the higher one doesn't exist, e.g.:

var mm map[int]map[int]int
mm[1][2] = 3

But it also happens for a simple map (though with struct as a key):

package main

import "fmt"

type COO struct {
    x int
    y int
}

var neighbours map[COO][]COO

func main() {
    for i := 0; i < 30; i++ {
        for j := 0; j < 20; j++ {
            var buds []COO
            if i < 29 {
                buds = append(buds, COO{x: i + 1, y: j})
            }
            if i > 0 {
                buds = append(buds, COO{x: i - 1, y: j})
            }
            if j < 19 {
                buds = append(buds, COO{x: i, y: j + 1})
            }
            if j > 0 {
                buds = append(buds, COO{x: i, y: j - 1})
            }
            neighbours[COO{x: i, y: j}] = buds // <--- yields error
        }
    }


    fmt.Println(neighbours)

}

What could be wrong?

  • 写回答

2条回答 默认 最新

  • douyuqing_12345 2016-06-03 18:55
    关注

    You need to initialize neighbours: var neighbours = make(map[COO][]COO)

    See the second section in: https://blog.golang.org/go-maps-in-action

    You'll get a panic whenever you try to insert a value into a map that hasn't been initialized.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛