How to initialize values for nested struct array in golang

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:

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 Objects array) that hasn’t been allocated yet.

For arrays of structs, this needs to be done with make.

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

Then, in order to add to your array safely, you’re better off instantiating an individual MyStruct, i.e.

ms := MyStruct{
    MyField: 10,
}

And then appending this to your r.Objects array

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

For more information about make, see the docs

Leave a Comment