diff --git a/maputil/map.go b/maputil/map.go index 9cd19c8..c130792 100644 --- a/maputil/map.go +++ b/maputil/map.go @@ -582,9 +582,12 @@ func convertSlice(src reflect.Value, dst reflect.Value) error { return fmt.Errorf("error type:%s", dst.Type().String()) } l := src.Len() - target := reflect.MakeSlice(dst.Type(), l, l) - if dst.CanSet() { - dst.Set(target) + if dst.Kind() == reflect.Array { + if l > dst.Len() { + return fmt.Errorf("source length %d exceeds destination length %d", l, dst.Len()) + } + } else if dst.CanSet() { + dst.Set(reflect.MakeSlice(dst.Type(), l, l)) } for i := 0; i < l; i++ { srcValue := src.Index(i) diff --git a/maputil/map_test.go b/maputil/map_test.go index 436cdae..378d813 100644 --- a/maputil/map_test.go +++ b/maputil/map_test.go @@ -11,6 +11,16 @@ import ( "github.com/duke-git/lancet/v2/internal" ) +func TestMapToArray(t *testing.T) { + var dst [2]int + if err := MapTo([]int{3, 4}, &dst); err != nil || dst != [2]int{3, 4} { + t.Fatalf("got %v, %v", dst, err) + } + if err := MapTo([]int{1, 2, 3}, &dst); err == nil { + t.Fatal("expected an error for an oversized source") + } +} + func TestMapToStructInvalidInputs(t *testing.T) { var nilTarget *struct { Name string `json:"name"`