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
}
Run Code Online (Sandbox Code Playgroud)
What do I need to change so that my function initializes a 2D array?
表达方式:
make([][]bool, sizeX)
Run Code Online (Sandbox Code Playgroud)
将创建一个[]bool
大小为 s 的切片sizeX
。然后你必须遍历每个元素并将它们初始化为sizeY
. 如果你想要一个完全初始化的数组:
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)
}
Run Code Online (Sandbox Code Playgroud)
该表达式make([][]bool, sizeX, sizeY)
创建一个[][]bool
具有初始大小sizeX
和容量的切片sizeY
。