英文:
Creating a slice of slice of interfaces in go
问题
我正在尝试创建一个函数,将map
的所有key, value
作为slice
的slice
返回,其中每个元组为{key, value}
。
以下是代码:
func ReturnTuples(map_ map[interface{}]interface{}) [][]interface{} {
toReturn := [][]interface{}{}
...
但是在toReturn
这一行我遇到了错误:
type [][]interface {} is not an expression
我应该如何声明一个接口的切片的切片?我认为这是唯一的方法。我尝试了没有括号的方式:
[][]interface{}
但这也不起作用。
我尝试在谷歌上搜索“golang slice of slice”,但只有很少的结果。例如,我只找到了如何创建一个由uint8
组成的简单切片,即[][]uint8
。
英文:
I'm trying to create a function that returns the all the key, value
of a map
as a slice
of slice
of tuples (where each tuple is {key, value}
)
Here's the code:
func ReturnTuples(map_ map[interface{}]interface{}) [][]interface{} {
toReturn := []([]interface{})
...
But I'm getting error for the toReturn
line:
type [][]interface {} is not an expression
How should I declare a slice of slice of interfaces? I see this as the only way. I tried without parenthesis like:
[][]interface{}
but it won't work either.
I tried to search for 'golang slice of slice' on google but very few things appear. For example I've only found how to create a simple one made of uint8
, which is: [][]uint8
.
答案1
得分: 3
切片的元素类型是interface{}
,因此需要额外添加一对花括号来创建复合字面量:[]interface{}{}
。
如果是切片的切片:
toReturn := [][]interface{}{}
或者使用make()
函数时,需要指定一个_类型_(而不是复合字面量):
toReturn := make([][]interface{}, 0, len(map_))
英文:
The element type of the slice is interface{}
, so a composite literal needs an additional pair of braces: []interface{}{}
.
In case of slice of slices:
toReturn := [][]interface{}{}
Or when using make()
, you specify a type (and not a composite literal):
toReturn := make([][]interface{}, 0, len(map_))
答案2
得分: 2
你正在创建一个实例,而不是定义一个类型,所以你需要额外的一对花括号来初始化变量:
toReturn := [][]interface{}{}
英文:
You're creating an instance, not defining a type, so you need an extra pair of curly braces to initialize the variable:
toReturn := [][]interface{}{}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论