Skip to content

Instantly share code, notes, and snippets.

@heri16
Created July 26, 2021 10:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save heri16/077282d46ae95d48d430a90fb6accdff to your computer and use it in GitHub Desktop.
Save heri16/077282d46ae95d48d430a90fb6accdff 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

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
}

@lnnt
Copy link

lnnt commented Dec 28, 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
}

How about this?

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

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