summaryrefslogtreecommitdiff
path: root/internal/conv/conv.go
blob: 29dca28e8351f0a000a3e2e1d2ca63fe745dd93a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package conv

import (
	"fmt"
	"reflect"
)

// InterfaceSlice converts an array or slice of any type into an []any
// for use in functions that expect this.
func InterfaceSlice(slice any) ([]any, error) {
	// avoid all this nonsense if this is already a []any...
	if s, ok := slice.([]any); ok {
		return s, nil
	}
	s := reflect.ValueOf(slice)
	kind := s.Kind()
	switch kind {
	case reflect.Slice, reflect.Array:
		l := s.Len()
		ret := make([]any, l)
		for i := range l {
			ret[i] = s.Index(i).Interface()
		}
		return ret, nil
	default:
		return nil, fmt.Errorf("expected an array or slice, but got a %T", s)
	}
}