Golang - convert slice such as []string to []interface{}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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