登录
首页 >  Golang >  Go问答

如何在 Golang 中初始化空地图并添加新的键值对?

来源:stackoverflow

时间:2024-03-26 08:12:32 126浏览 收藏

在 Go 语言中,初始化空地图并添加键值对时,需注意 append 函数只能用于切片,而不能用于地图。要向地图中添加数据,需要使用 make 函数创建地图的切片,然后逐个向切片中添加数据。

问题内容

我在创建空地图并在另一张地图上循环时向其附加新数据时遇到问题。

这是我在 ide 上遇到的错误。

这是我要添加到地图中的数据结构。

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
}

我基本上希望将如下所示的内容保存在数据库中。

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

我是 golang 新手,感谢您的帮助。谢谢


解决方案


正如错误明确指出的那样:

这意味着您需要在将数据附加到结果之前创建一个切片,这实际上是结果的切片,就像您在所需的输出中提到的那样。

创建 outcomes 的切片,然后将 entrypicks 中的数据附加到该切片:

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),
    })
}

这将让您提供您想要的结果。

理论要掌握,实操不能落!以上关于《如何在 Golang 中初始化空地图并添加新的键值对?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>