如何在 Go 中分配一个非常量大小的二维数组?

Nic*_*ler 2 arrays matrix go

我想为二维数组分配空间,我想以一种干净的方式这样做。

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)
Run Code Online (Sandbox Code Playgroud)

第一次尝试时出现错误:

非常量数组绑定 l

PS未解决:如何在Go中分配非常量大小的数组

Not*_*fer 6

没有“一个班轮”的方式来做到这一点。简单地做:

matrix := make([][]int, myLength)
for i : = 0; i < myLength; i++ {
   matrix[i] = make([]int, myLength)
}
Run Code Online (Sandbox Code Playgroud)