doumei8126 2017-10-22 05:15
浏览 126
已采纳

为什么这段代码会超出范围生成数组索引?

I am stuck for past 5 - 6 hours in figuring this out that why this code is generating array index out of bound error on run time. I am unable to find out the reason. Can you please tell what modifications are required to correct this code?

spotsArr        := make(map[int][]map[int64][]int)
for ind, availableSpot := range availableSpots {
            spotsArr[availableSpot.Uid][ind] = make(map[int64][]int)
            spotsArr[availableSpot.Uid][ind][availableSpot.Date] = []int{availableSpot.SpotSlug}

}
fmt.Println(spotsArr)

Edit 1: View the full code here https://play.golang.org/p/Smm0BFgtNp

Edit 2: Actually what I need to do is to get output in format something like:

{ uid: { date: {spot_slug, spot_slug} } }

{ 86: { 1536710400: {1000, 1200, 900},
      { 1536105600: {900} } }
  • 写回答

2条回答 默认 最新

  • dtvam48220 2017-10-22 06:43
    关注

    The error is, as the error message suggests, because you tried to assign element on the index greater than the slice length. For the sake of getting the error away, you can just initialize the slice to the length, at least, as much as the index you wanted to use :

    ....
    spotsArr[availableSpot.Uid] = make([]map[int64][]int, ind+1, ind+1)
    spotsArr[availableSpot.Uid][ind] = make(map[int64][]int)
    ....
    

    But as you clarified further about the desired output, it seems that you don't need slice in the first place. You need map of Uid where each key has value of map of Date :

    spotsArr := make(map[int]map[int64][]int)
    for _, availableSpot := range availableSpots {
        if _, ok := spotsArr[availableSpot.Uid]; !ok {
            spotsArr[availableSpot.Uid] = make(map[int64][]int)
        }
        spotsArr[availableSpot.Uid][availableSpot.Date] = append(spotsArr[availableSpot.Uid][availableSpot.Date],availableSpot.SpotSlug)
    }
    fmt.Println(spotsArr)
    

    <kbd>playground</kbd>

    Given the last two data have the same date, the output is as follows :

    map[86:map[1534896000:[900] 1535500800:[900] 1536105600:[900] 1537315200:[900 900]]]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决,来真人,不要ai!
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法