Add slices/ helper pkg

pull/2/head
Vinícius Garcia 2020-09-11 19:48:32 -03:00
parent fbb7d9ffca
commit e7a7b13eef
1 changed files with 29 additions and 0 deletions

29
slices/slices.go Normal file
View File

@ -0,0 +1,29 @@
package slices
import "reflect"
type ToInterfaceSlicer interface {
ToInterfaceSlice() []interface{}
}
func ToInterfaceSlice(slice interface{}) (resp []interface{}) {
if iSlicer, ok := slice.(ToInterfaceSlicer); ok {
return iSlicer.ToInterfaceSlice()
}
v := reflect.ValueOf(slice)
t := v.Type()
if t.Kind() != reflect.Slice {
panic("ToInterfaceSlice function only works with a slice as argument")
}
if t.Kind() != reflect.Slice {
panic("type must be a slice!")
}
for i := 0; i < v.Len(); i++ {
resp = append(resp, v.Index(i).Interface())
}
return resp
}