diff --git a/sliceutil/sliceutil.go b/sliceutil/sliceutil.go index 0b24043..a4f1a40 100644 --- a/sliceutil/sliceutil.go +++ b/sliceutil/sliceutil.go @@ -192,6 +192,15 @@ func InterfaceSliceTo(src []interface{}, dst interface{}) interface{} { return dstV.Interface() } +// ToAnySlice converts a slice of T to a slice of any. +func ToAnySlice[T any](tt []T) []any { + ret := make([]any, len(tt)) + for i, t := range tt { + ret[i] = t + } + return ret +} + // Values returns a list of items extracted from T, see test file for example func Values[T comparable, N any](tt []T, fn func(T) N) []N { ret := make([]N, len(tt)) diff --git a/sliceutil/sliceutil_test.go b/sliceutil/sliceutil_test.go index caa9162..29443c5 100644 --- a/sliceutil/sliceutil_test.go +++ b/sliceutil/sliceutil_test.go @@ -622,6 +622,16 @@ func TestInterfaceSliceTo(t *testing.T) { } } +func TestToAnySlice(t *testing.T) { + in := []int{1, 2, 3, 4, 5} + out := ToAnySlice(in) + for i := range out { + if !reflect.DeepEqual(out[i], in[i]) { + t.Errorf("want %[1]v(%[1]T),\tgot %[2]v(%[2]T)", in[i], in[i]) + } + } +} + func TestValues(t *testing.T) { type testStruct struct { Name string