在Go语言中创建一个接口的切片的切片。

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

Creating a slice of slice of interfaces in go

问题

我正在尝试创建一个函数,将map的所有key, value作为sliceslice返回,其中每个元组为{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{}{}

huangapple
  • 本文由 发表于 2017年2月23日 18:23:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/42412935.html
匿名

发表评论

匿名网友

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

确定