Initializing an empty array of struct type in golang

Viewed 38934

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.

4 Answers

If you print the length of day, you will get 0, so you cannot access day[0], which does not exist.

You can write it in this way: day = append(day, DayAndTime{"Monday", "8.00 PM"})

This should be the right syntax in your example:

type DayAndTime struct {
    days string
    time string
}

days := []*DayAndTime{}
Related