Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize values for nested struct array in golang

Tags:

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?

like image 832
vanarajcs Avatar asked Nov 24 '15 11:11

vanarajcs


People also ask

How to declare an array of structures in Golang?

Declaring and initializing an Array of Structs We simply declare an array with the type of that struct. 2. Inserting values in an Array of Structs Use append function which returns the slice after insertion. Or, we can simply use indexing like this. This is how we can use structs in Go for various purposes.

How to assign default value for struct field in Golang?

How to Assign Default Value for Struct Field in Golang? - GeeksforGeeks How to Assign Default Value for Struct Field in Golang? Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.

What is nested structure in Go language?

Go language allows nested structure. A structure which is the field of another structure is known as Nested Structure. Or in other words, a structure within another structure is known as a Nested Structure. type struct_name_1 struct { // Fields } type struct_name_2 struct { variable_name struct_name_1 }

How to create and initialize a struct in go?

Creating and initializing a Struct in GoLang 1 Using struct Literal Syntax Struct literal syntax is just assigning values when declaring and it is really easy. ... 2 Using the new keyword We can use the new keyword when declaring a struct. Then we can assign values using dot notation to initialize it. ... 3 Using pointer address operator


1 Answers

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

like image 81
mattsch Avatar answered Sep 16 '22 12:09

mattsch