Golang嵌套结构切片 - 错误索引超出范围

时间:2018-03-22 09:12:07

标签: arrays go struct slice

Playground

我试图将字符串存储到结构内的切片字段中。这是为了收集数据并创建一个Json以通过API发布。

package main

type response1 struct {
Identifier string `json:"identifier"`
Family     string `json:"family"`
Values     struct {
    Logo []struct {
        Data string `json:"data"`
        Scope string `json:"scope"`
    } `json:"logo"`
  }
}

func main() {

    res2D := &response1{
        Identifier: "1234567",
        Family:     "example",
    }

    res2D.Values.Logo[0].Data = "test"

    res2B, _ := json.Marshal(res2D)

    fmt.Println(string(res2B))
}

错误

我得到的错误:

panic: runtime error: index out of range

goroutine 1 [running]:
main.main()
    /tmp/sandbox507443306/main.go:22 +0xe0

1 个答案:

答案 0 :(得分:0)

您手边没有make具有适当大小的切片。你可以使用追加。您在示例中尝试执行的操作是分配尚未创建的切片“[0]”,这就是您收到错误的原因。使用追加并更改你的行

res2D.Values.Logo[0].Data = "test"

res2D.Values.Logo = append(res2D.Values.Logo,struct {Data string "json:\"data\"" }{Data: "test"})

然后将文字结构附加到您的数组中。现在通过查看你的代码,我假设你这样做是为了探索语言的测试,所以我不会详细介绍如何在不知道你实际使用它的情况下更好地编写它。

相关问题