summaryrefslogtreecommitdiff
path: root/internal/conv/conv.go
blob: d953296c3f22db54ecbad63bc9de61ae72c9e0df (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
29
package conv

import (
	"reflect"

	"github.com/pkg/errors"
)

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