[英]golang: how to use make() function to generate 2-demensional slice?
First I declared variable p
in one place:首先,我在一个地方声明了变量
p
:
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
:然后在另一个 function 中,我尝试初始化
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.
谢谢。
The declaration of p
here indicates a 2D array.这里的
p
声明表示一个二维数组。 You can convert it to a 2D Slice:您可以将其转换为 2D 切片:
var p [][]int
This should then work as expected when allocation is done via make()
.当通过
make()
完成分配时,这应该会按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.