From e7a7b13eef1ac5d99c9b7d0ba660acc252b24443 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Fri, 11 Sep 2020 19:48:32 -0300 Subject: [PATCH] Add slices/ helper pkg --- slices/slices.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 slices/slices.go diff --git a/slices/slices.go b/slices/slices.go new file mode 100644 index 0000000..583384e --- /dev/null +++ b/slices/slices.go @@ -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 +}