fix(maputil): map slices into array destinations (#371)

This commit is contained in:
Yusuf Efe authored and GitHub committed 2026-10-23 20:53:52 +08:00
1 parent 4db163b4b7
commit 65806afc7d
2 files changed
+16 -3

No files matched your search

+6 -3
View File
@@ -582,9 +582,12 @@ func convertSlice(src reflect.Value, dst reflect.Value) error {
return fmt.Errorf("error type:%s", dst.Type().String()) return fmt.Errorf("error type:%s", dst.Type().String())
} }
l := src.Len() l := src.Len()
target := reflect.MakeSlice(dst.Type(), l, l) if dst.Kind() == reflect.Array {
if dst.CanSet() { if l > dst.Len() {
dst.Set(target) 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++ { for i := 0; i < l; i++ {
srcValue := src.Index(i) srcValue := src.Index(i)
+10
View File
@@ -11,6 +11,16 @@ import (
"github.com/duke-git/lancet/v2/internal" "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) { func TestMapToStructInvalidInputs(t *testing.T) {
var nilTarget *struct { var nilTarget *struct {
Name string `json:"name"` Name string `json:"name"`