My goal is to declare an empty 2D array that is then initialized and then filled with values every time do() runs. The issue is that I am getting a nil pointer dereference even though I am initializing the array.
This is a simple version of what I am trying to accomplish on a server simulator.
package main
import "fmt"
type Srv struct {
A *[][]int
}
func (s Srv) init() {
arr := make([][]int, 0)
*s.A = arr
}
func main() {
s := Srv{nil}
s.init()
printSlice(*s.A)
do(s.A)
do(s.A)
}
func printSlice(s [][]int) {
fmt.Printf("len=%d cap=%d %v
", len(s), cap(s), s)
}
func do(s *[][]int) {
*s = append(*s, make([]int, 0))
printSlice(*s)
(*s)[0] = append((*s)[0], 5)
(*s)[0] = append((*s)[0], 6)
*s = append(*s, make([]int, 0))
printSlice(*s)
}
I expect an output like [ [5 6 5 6] [] [] [] ] but instead I get nil pointer dereference.
Where init does *s.A =
, it's dereferencing a nil pointer. s.A
is not yet initialized at that point (i.e., it's nil
), and *
is the dereference operator. But it's only a problem because it's unnecessarily complicated in the first place. It should just be:
func (s Srv) init() {
s.A = make([][]int, 0)
}