user6791424
user6791424

Reputation:

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.

Upvotes: 4

Views: 1614

Answers (2)

icza
icza

Reputation: 418745

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_))

Upvotes: 3

Not_a_Golfer
Not_a_Golfer

Reputation: 49283

You're creating an instance, not defining a type, so you need an extra pair of curly braces to initialize the variable:

toReturn := [][]interface{}{}

Upvotes: 2

Related Questions