Skip to content

Instantly share code, notes, and snippets.

@heri16
Created Jul 26, 2021
Embed
What would you like to do?
Golang - convert slice such as []string to []interface{}
module slice
func InterfaceSlice(slice interface{}) []interface{} {
switch slice := slice.(type) {
case []string:
new := make([]interface{}, len(slice))
for i, v := range slice {
new[i] = v
}
return new
case []int:
new := make([]interface{}, len(slice))
for i, v := range slice {
new[i] = v
}
return new
default:
sliceV := reflect.ValueOf(slice)
if sliceV.Kind() != reflect.Slice {
panic("InterfaceSlice() given a non-slice type")
}
// Keep the distinction between nil and empty slice input
if sliceV.IsNil() {
return nil
}
ret := make([]interface{}, sliceV.Len())
for i := 0; i < sliceV.Len(); i++ {
ret[i] = sliceV.Index(i).Interface()
}
return ret
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment