2

I am trying to simplay make a 2D array as a field on an object. I want a function that creates the object and returns it. But when trying to create the 2d array it returns a single array.

type Struct struct {
    X int
    Y int
    Grid [][]bool
}

func NewLifeSimulator(sizeX, sizeY int) *Struct{
    s := &Struct{
        X:    sizeX,
        Y:    sizeY,
        Grid: make([][]bool, sizeX,sizeY),  //Creates a regular array instead of 2D
    }
    return s
}

What do I need to change so that my function initializes a 2D array?

TannerHelms12
  • 43
  • 1
  • 6

1 Answers1

5

The expression:

make([][]bool, sizeX)

will create a slice of []bools of size sizeX. Then you have to go through each element and initialize those to slices of sizeY. If you want a fully initialized array:

s := &Struct{
        X:    sizeX,
        Y:    sizeY,
        Grid: make([][]bool, sizeX),
    }

// At this point, s.Grid[i] has sizeX elements, all nil

for i:=range s.Grid {
   s.Grid[i]=make([]bool, sizeY)
}

The expression make([][]bool, sizeX, sizeY) creates a [][]bool slice with initial size sizeX and capacity sizeY.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59