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