How to initialize values for nested struct array in golang

前端 未结 3 1539
鱼传尺愫
鱼传尺愫 2021-02-12 18:04

My struct

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

Initialize values for this

func mai         


        
3条回答
  •  余生分开走
    2021-02-12 18:57

    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{
        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.

提交回复
热议问题