This question already has an answer here:
How to allocate a non-constant sized array in Go

(1个答案)


4年前关闭。




我想为二维数组分配空间,并且我想以一种干净的方式分配空间。
address [10]int
myLength := len(address)

// 1. but this not work at all
matrix := [myLength][myLength]byte

// 2. and this initializes 10 arrays with length 0
matrix := make([][]int, myLength, myLength)

我第一次尝试时遇到错误:



PS无法解决:How to allocate a non-constant sized array in Go

最佳答案

没有“一个类轮”的方式可以做到这一点。只需做:

matrix := make([][]int, myLength)
for i : = 0; i < myLength; i++ {
   matrix[i] = make([]int, myLength)
}

08-25 21:28