简体   繁体   English

如何在golang中初始化嵌套结构数组的值

[英]How to initialize values for nested struct array in golang

My struct我的结构

type Result struct {
   name   string
   Objects []struct {
       id int
   }
}

Initialize values for this为此初始化值

func main() {
   var r Result;
   r.name  = "Vanaraj";
   r.Objects[0].id = 10;
   fmt.Println(r)
}

I got this error.我收到了这个错误。 "panic: runtime error: index out of range" “恐慌:运行时错误:索引超出范围”

How to fix this?如何解决这个问题?

Firstly, I'd say it's more idiomatic to define a type for your struct, regardless of how simple the struct is.首先,我会说为结构定义类型更为惯用,无论结构有多简单。 For example:例如:

type MyStruct struct {
    MyField int
}

This would mean changing your Result struct to be as follows:这意味着将您的Result结构更改为如下:

type Result struct {
    name   string
    Objects []MyStruct
}

The reason your program panics is because you're trying to access an area in memory (an item in your Object s array) that hasn't been allocated yet.您的程序发生混乱的原因是您正试图访问尚未分配的内存区域(您的Object数组中的一项)。

For arrays of structs, this needs to be done with make .对于结构数组,这需要使用make完成。

r.Objects = make([]MyStruct, 0)

Then, in order to add to your array safely, you're better off instantiating an individual MyStruct , ie然后,为了安全地添加到您的数组中,您最好实例化一个单独的MyStruct ,即

ms := MyStruct{
    MyField: 10,
}

And then append ing this to your r.Objects array然后append到您的r.Objects数组

r.Objects = append(r.Objects, ms)

For more information about make , see the docs有关make更多信息,请参阅文档

After defining the struct as suggested in another answer :按照另一个答案中的建议定义结构后:

type MyStruct struct {
    MyField int
}


type Result struct {
    Name   string
    Objects []MyStruct
}

Then you can initialize a Result object like this:然后你可以像这样初始化一个Result对象:

result := Result{
    Name: "I am Groot",
    Objects: []MyStruct{
        {
            MyField: 1,
        },
        {
            MyField: 2,
        },
        {
            MyField: 3,
        },
    },
}

Full code:完整代码:

package main

import "fmt"

func main() {
    result := Result{
        Name: "I am Groot",
        Objects: []MyStruct{
            {
                MyField: 1,
            },
            {
                MyField: 2,
            },
            {
                MyField: 3,
            },
        },
    }

    fmt.Println(result)

}

type MyStruct struct {
    MyField int
}

type Result struct {
    Name    string
    Objects []MyStruct
}

You can verify this in this Go playground .您可以在此Go 游乐场中验证这一点。

Objects contains no elements. Objects包含任何元素。 You need to append element first.您需要先append元素。 Like this:像这样:

r.Objects = append(r.Objects, struct{ id int }{}) 

Also you can omit r.Objects[0].id = 10;你也可以省略r.Objects[0].id = 10; using initialization of your struct like this:像这样使用结构的初始化:

r.Objects = append(r.Objects, struct{ id int }{ 10 })

This is probably a dumb idea, but you can roundtrip it through JSON:这可能是一个愚蠢的想法,但您可以通过 JSON 来回传递它:

package main

import (
   "bytes"
   "encoding/json"
)

type (
   a []interface{}
   m map[string]interface{}
)

func decode(in, out interface{}) {
   var b bytes.Buffer
   json.NewEncoder(&b).Encode(in)
   json.NewDecoder(&b).Decode(out)
}

Example:例子:

package main
import "fmt"

type result struct {
   Name string
   Objects []struct {
      Id int
   }
}

func main() {
   r := m{
      "Name": "Vanaraj",
      "Objects": a{
         m{"Id": 10},
      },
   }
   var s result
   decode(r, &s)
   fmt.Printf("%+v\n", s) // {Name:Vanaraj Objects:[{Id:10}]}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM