Skip to content

Commit

Permalink
Add function to convert []interface -> []string (#69)
Browse files Browse the repository at this point in the history
* Add function to convert []interface -> []string
  • Loading branch information
cesartw authored Mar 14, 2022
1 parent 194b7ef commit 637fa45
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
22 changes: 22 additions & 0 deletions sliceutil/sliceutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package sliceutil // import "github.com/teamwork/utils/sliceutil"

import (
"math/rand"
"reflect"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -214,3 +215,24 @@ func StringMap(list []string, f func(string) string) []string {

return ret
}

// InterfaceSliceTo converts []interface to any given slice.
// It will ~optimistically~ try to convert interface item to the dst item type
func InterfaceSliceTo(src []interface{}, dst interface{}) interface{} {
dstt := reflect.TypeOf(dst)
if dstt.Kind() != reflect.Slice {
panic("`dst` is not an slice")
}

dstV := reflect.ValueOf(dst)

for i := range src {
if i < dstV.Len() {
dstV.Index(i).Set(reflect.ValueOf(src[i]).Convert(dstt.Elem()))
continue
}
dstV = reflect.Append(dstV, reflect.ValueOf(src[i]).Convert(dstt.Elem()))
}

return dstV.Interface()
}
46 changes: 46 additions & 0 deletions sliceutil/sliceutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -528,3 +528,49 @@ func TestStringMap(t *testing.T) {
})
}
}

func TestInterfaceSliceTo(t *testing.T) {
{
src := []interface{}{"1", "2", "3", "4", "5"}
want := []string{"1", "2", "3", "4", "5"}
input := []string{""}

result := InterfaceSliceTo(src, input)
if !reflect.DeepEqual(result, want) {
t.Fatalf("want %+v(%T),\tgot %+v(%T)", want, want, result, result)
}
}

{
src := []interface{}{"1", "2", "3", "4", "5"}
want := []string{"1", "2", "3", "4", "5"}
input := []string{}

result := InterfaceSliceTo(src, input)
if !reflect.DeepEqual(result, want) {
t.Fatalf("want %+v(%T),\tgot %+v(%T)", want, want, result, result)
}
}

{
src := []interface{}{1, 2, 3, 4, 5}
want := []int{1, 2, 3, 4, 5}
input := []int{0, 0}

result := InterfaceSliceTo(src, input)
if !reflect.DeepEqual(result, want) {
t.Fatalf("want %+v(%T),\tgot %+v(%T)", want, want, result, result)
}
}

{
src := []interface{}{1, 2, 3, 4, 5}
want := []int64{1, 2, 3, 4, 5}
input := []int64{0, 0}

result := InterfaceSliceTo(src, input)
if !reflect.DeepEqual(result, want) {
t.Fatalf("want %+v(%T),\tgot %+v(%T)", want, want, result, result)
}
}
}

0 comments on commit 637fa45

Please sign in to comment.