Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a slice of slice of interfaces in go

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 Answers

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_))
like image 124
icza Avatar answered Sep 20 '25 17:09

icza