golang: how to use make() function to generate 2-demensional slice?

huangapple go评论89阅读模式
英文:

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().

huangapple
  • 本文由 发表于 2022年8月21日 12:19:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/73431622.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定