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 ...}
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.
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)
Two slices can be concatenated using append method in the standard golang library. Which is similar to the variadic function operation.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With