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?
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? - 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.
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 }
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
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 Object
s 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 append
ing this to your r.Objects
array
r.Objects = append(r.Objects, ms)
For more information about make
, see the docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With