Skip to content

Instantly share code, notes, and snippets.

@futurist
Forked from heri16/slice.go
Created July 2, 2022 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save futurist/b19b98371fde3895da794fc11780fdb2 to your computer and use it in GitHub Desktop.
Save futurist/b19b98371fde3895da794fc11780fdb2 to your computer and use it in GitHub Desktop.
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
}
}
@futurist
Copy link
Author

futurist commented Jul 2, 2022

This can be done using 1.18 with generic:

func InterfaceSlice [P any] (slice []P) []any {
	ret := make([]any, len(slice))
	for i:=0; i < len(slice); i++ {
		v := slice[i]
		ret[i] = any(v)
	}
	return ret
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment