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()
}