Skip to content

Commit

Permalink
Enhancement: sliceutil - New function to convert any slice to any
Browse files Browse the repository at this point in the history
Some libraries require providing `[]any` as input, and this function would be
handy for dropping boring loop conversions.
  • Loading branch information
rafaeljusto committed Oct 17, 2024
1 parent d630e9a commit 5d4902e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions sliceutil/sliceutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
10 changes: 10 additions & 0 deletions sliceutil/sliceutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 5d4902e

Please sign in to comment.