I have the following:
type Int32A int32
type Int32B int32
and would like to implement a function that can accept any slice of types whose kind is reflect.Int32 and convert it into []int32. For example:
func ConvertTypeSliceToInt32Slice(es «es-type») []int32 {
result := make([]int32, len(es))
for i := 0; i < len(result); i++ {
result[i] = es[i].(int32)
}
return result
}
func caller() {
Int32as := Int32A{1, 2}
Int32bs := Int32B{3, 5}
int32as := ConvertTypeSliceToInt32Slice(Int32as)
int32bs := ConvertTypeSliceToInt32Slice(Int32bs)
}
How can this be done far any arbitrary type definition whose kind is reflect.Int32? (Context: this function will be used to convert slices of proto enums; ie the full set of types is unknown and unbounded so performing a switch on each type isn't feasible).
Also, I'm using 1.17 so I can't use parameterized types (aka templates).
One attempt that doesn't work (it panics at is.([]interface{})):
func ConvertTypeSliceToInt32Slice(is interface{}) []int32 {
es := is.([]interface{})
result := make([]int32, len(es))
for i := 0; i < len(result); i++ {
result[i] = es[i].(int32)
}
return result
}