golang中不同类型的切片切片
Slice of slices with different types in golang
背景:想利用golang中的切片数据结构做一个二维特征向量。这个特征向量应该是一个slice,由不同类型的slice组成,有时是strings,int,float64等
到目前为止,我可以用地图实现这个(下图),有没有办法用切片实现这个?
map := make(map[int]interface{}}
应该更像什么:
featureVector := []interface{[]int, []float64, []string ...}
它按预期工作,您只是使用了错误的语法。切片的元素类型是 interface{}
,因此初始化它的 composite literal 应该类似于 []interface{}{ ... }
,如本例所示:
featureVector := []interface{}{[]int{1, 2}, []float64{1.2, 2.2}, []string{"a", "b"}}
您可以像对待任何其他切片一样对待它:
featureVector = append(featureVector, []byte{'x', 'y'})
fmt.Printf("%#v", featureVector)
输出(在 Go Playground 上尝试):
[]interface{}{[]int{1, 2}, []float64{1.2, 2.2}, []string{"a", "b"}, []uint8{0x78, 0x79}}
但是要知道,由于元素类型是 interface{}
,没有什么可以阻止任何人附加非切片:
featureVector = append(featureVector, "abc") // OK
这也适用于 map
解决方案。
背景:想利用golang中的切片数据结构做一个二维特征向量。这个特征向量应该是一个slice,由不同类型的slice组成,有时是strings,int,float64等
到目前为止,我可以用地图实现这个(下图),有没有办法用切片实现这个?
map := make(map[int]interface{}}
应该更像什么:
featureVector := []interface{[]int, []float64, []string ...}
它按预期工作,您只是使用了错误的语法。切片的元素类型是 interface{}
,因此初始化它的 composite literal 应该类似于 []interface{}{ ... }
,如本例所示:
featureVector := []interface{}{[]int{1, 2}, []float64{1.2, 2.2}, []string{"a", "b"}}
您可以像对待任何其他切片一样对待它:
featureVector = append(featureVector, []byte{'x', 'y'})
fmt.Printf("%#v", featureVector)
输出(在 Go Playground 上尝试):
[]interface{}{[]int{1, 2}, []float64{1.2, 2.2}, []string{"a", "b"}, []uint8{0x78, 0x79}}
但是要知道,由于元素类型是 interface{}
,没有什么可以阻止任何人附加非切片:
featureVector = append(featureVector, "abc") // OK
这也适用于 map
解决方案。