douguxun6866 2018-09-24 02:25
浏览 101

我们如何创建一个空地图并在golang中添加新数据?

I'm having a problem with creating an empty map and append new data to it while looping on another map.

this is the error i'm getting on my IDE.

enter image description here

here's my data struct to be added to the map.

type Outcome struct {
QuestionIndex string
ChoiceIndex   int64
Correct       bool
}

func createEntryOutcome(e *entry.Entry) map[string]interface{} {
entryPicks := e.Live.Picks
outcomes := make(map[string]interface{})
for idx, pick := range entryPicks {
    mappedPick := pick.(map[string]interface{})
    outcomes = append(outcomes, Outcome{
        QuestionIndex: idx,
        ChoiceIndex:   mappedPick["index"].(int64),
        Correct:       mappedPick["correct"].(bool),
    })
}
return outcomes
}

i basically want something like below to be saved in the database.

[
  {
    qIndex: "1",
    cIndex: 1,
    correct: false,
  },
  {
    qIndex: "1",
    cIndex: 1,
    correct: false,
  },
]

im new to golang and any help is appreciated. thanks

  • 写回答

2条回答 默认 最新

  • douxuqiao6394 2018-09-24 03:49
    关注

    As the error clearly says:

    first argument to append must be slice; have map[string]interface{}

    which means you need to create a slice before appending the data to outcomes which is actually slice of outcomes, like you have mentioned in the output you want.

    The append function appends the elements x to the end of the slice s, and grows the slice if a greater capacity is needed.

    Create a slice of outcomes and then append the data from entryPicks to that slice:

    outcomes := make([]map[string]interface{})
    for idx, pick := range entryPicks {
        mappedPick := pick.(map[string]interface{})
        outcomes = append(outcomes, Outcome{
            QuestionIndex: idx,
            ChoiceIndex:   mappedPick["index"].(int64),
            Correct:       mappedPick["correct"].(bool),
        })
    }
    

    which will let you provide the outcome you want.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看