Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an empty array of struct type in golang

Tags:

arrays

struct

go

I have initialized a struct :

type DayAndTime struct {
    days string
    time string
  }

I have initialized an empty set of array of this DayAndTime type:

day := []DayAndTime{}

And put a value in it: day[0] = DayAndTime{"Monday", "8.00 PM"}

But it shows a runtime error:

panic: runtime error: invalid memory address or nil pointer dereference

Why is this happenning and what could be a possible solution?

edit: It's actually a slice not an array.

like image 640
Soumya Rauth Avatar asked Sep 17 '17 07:09

Soumya Rauth


People also ask

How do you define an empty struct in Go?

An empty struct is a struct type without fields struct{} . The cool thing about an empty structure is that it occupies zero bytes of storage.

How do you use an array of structs in Golang?

In the Go language, you can set a struct of an array. To do so see the below code example. Where type company struct has a slice of type employee struct. Here, you can see the two different structs, and the employee struct is used as an array in the company struct.

How do I assign an empty slice in Golang?

To declare the type for a variable that holds a slice, use an empty pair of square brackets, followed by the type of elements the slice will hold.


1 Answers

Here you have a zero-length slice, the len and cap functions will both return 0 for a zero-valued slice

A slice cannot be grown beyond its capacity. Attempting to do so will cause a runtime panic, just as when indexing outside the bounds of a slice or array. Similarly, slices cannot be re-sliced below zero to access earlier elements in the array.

You may us make to initialize the slice with capacity and assign with index or use append to add values to slice

Both are valid code

var day []DayAndTime
day = append(day, DayAndTime{"Monday", "8.00 PM"})

or

var day = make([]DayAndTime, 1)
day[0] = DayAndTime{"Monday", "8.00 PM"}

Using append is recomended

Here is a sample code justifying/explaining the answer https://play.golang.org/p/ajsli-6Vqw

package main

import (
    "fmt"
)

type DayAndTime struct {
    days string
    time string
}

func ZeroLength() {
    var day = []DayAndTime{}
    fmt.Println("Hello, playground", cap(day), len(day), day)
}

func AppendArray() {
    var day = []DayAndTime{}
    day = append(day, DayAndTime{"Monday", "8.00 PM"})
    fmt.Println("Hello, playground", cap(day), len(day), day)
}

func SetIndex() {
    var day = make([]DayAndTime, 1)
    day[0] = DayAndTime{"Monday", "8.00 PM"}
    fmt.Println("Hello, playground", cap(day), len(day), day)
}

func main() {
    ZeroLength()
    AppendArray()
    SetIndex()
}
like image 171
Sarath Sadasivan Pillai Avatar answered Sep 19 '22 15:09

Sarath Sadasivan Pillai