英文:
golang: how to use make() function to generate 2-demensional slice?
问题
首先,我在一个地方声明了变量p
:
var p [2][]int
它是一个二维切片,每个维度的大小应该在运行时动态确定。
然后在另一个函数中,我尝试初始化p
:
n1 := ...
n2 := ...
p = make([][]int, 2) // 语法错误
p[0] = make([]int, n1) // 正确
p[1] = make([]int, n2) // 正确
语法错误是:
cannot use make([][]int, 2) (value of type [][]int) as [2][]int value in assignment(compiler)
如何修复它?谢谢。
英文:
First I declared variable p
in one place:
var p [2][]int
It's a 2d slice, and size of each dimension should be dynamically determined at run time.
Then in another function, I tried to initialize p
:
n1 := ...
n2 := ...
p = make([][]int, 2) // syntax error
p[0] = make([]int, n1) // ok
p[1] = make([]int, n2) // ok
The syntax error is:
cannot use make([][]int, 2) (value of type [][]int) as [2][]int value in assignment(compiler)
How to fix it? Thanks.
答案1
得分: 1
这里对 p
的声明表示一个二维数组。你可以将其转换为一个二维切片:
var p [][]int
当使用 make()
进行分配时,这样应该按预期工作。
英文:
The declaration of p
here indicates a 2D array. You can convert it to a 2D Slice:
var p [][]int
This should then work as expected when allocation is done via make()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论