Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice of slices with different types in golang

Tags:

slice

go

Context: I want to use the slice data structure in golang to make a 2-D feature vector. This feature vector should be a slice that consists of slices of different types, sometimes strings, int, float64 etc.

As of yet, I can achieve this with a map (below), is there a way to implement this with a slice?

map := make(map[int]interface{}}

What should be more like:

featureVector := []interface{[]int, []float64, []string ...}
like image 491
Nicky Feller Avatar asked Sep 13 '16 16:09

Nicky Feller


People also ask

How do you slice slices in Golang?

To make a slice of slices, we can compose them into multi-dimensional data structures similar to that of 2D arrays. This is done by using a function called make() which creates an empty slice with a non-zero length. This is shown in the following example: Go.

What types in Go can be used with a slice operator?

In Go, there are two functions that can be used to return the length and capacity of a slice: len() function - returns the length of the slice (the number of elements in the slice) cap() function - returns the capacity of the slice (the number of elements the slice can grow or shrink to)

Can you append a slice to a slice Golang?

Two slices can be concatenated using append method in the standard golang library. Which is similar to the variadic function operation.

How do I assign a value to a slice in Golang?

Go slice make function It allocates an underlying array with size equal to the given capacity, and returns a slice that refers to that array. We create a slice of integer having size 5 with the make function. Initially, the elements of the slice are all zeros. We then assign new values to the slice elements.


1 Answers

It works as expected, you're just using wrong syntax. The element type of the slice is interface{}, so a composite literal to initialize it should look like []interface{}{ ... }, like in this example:

featureVector := []interface{}{[]int{1, 2}, []float64{1.2, 2.2}, []string{"a", "b"}}

And you can treat it like any other slice:

featureVector = append(featureVector, []byte{'x', 'y'})
fmt.Printf("%#v", featureVector)

Output (try it on the Go Playground):

[]interface{}{[]int{1, 2}, []float64{1.2, 2.2}, []string{"a", "b"}, []uint8{0x78, 0x79}}

But know that since the element type is interface{}, nothing prevents anybody to append a non-slice:

featureVector = append(featureVector, "abc") // OK

This also applies to the map solution.

like image 173
icza Avatar answered Jan 19 '23 12:01

icza