How to initialize values ​​for nested struct array in golang

My structure

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 it?

+9
go
source share
3 answers

First, I would say that it is more idiomatic to define a type for your structure, regardless of how simple the structure is. For example:

 type MyStruct struct { MyField int } 

This would mean changing the Result structure as follows:

 type Result struct { name string Objects []MyStruct } 

The reason for your program panic is that you are trying to access an area in memory (an element in the Object array) that has not yet been allocated.

For arrays of structures, this must be done using make .

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

Then, to add to your array safely, you better create an instance of MyStruct , i.e.

 ms := MyStruct{ MyField: 10, } 

And then append enter this into your r.Objects array

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

For more information on make see the docs .

+13
source share

Objects contains no elements. First you need append . Like this:

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

You can also omit r.Objects[0].id = 10; using the initialization of its structure as follows:

 r.Objects = append(r.Objects, struct{ id int }{ 10 }) 
+3
source share

After defining the structure, as suggested in another answer :

 type MyStruct struct { MyField int } type Result struct { Name string Objects []MyStruct } 

Then you can initialize the Result object as follows:

 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 check it out on the Go playground .

0
source share

All Articles