Call Convert() in ConvertSlice() to ensure proper conversion of maps and nested slices

This commit is contained in:
Elara 2022-05-01 03:25:32 -07:00
parent cdaa7e88a6
commit 073ebbd8ba

View File

@ -72,10 +72,10 @@ func Convert(in reflect.Value, toType reflect.Type) (reflect.Value, error) {
if in.Type() == reflect.TypeOf([]any{}) && if in.Type() == reflect.TypeOf([]any{}) &&
to.Kind() == reflect.Slice || to.Kind() == reflect.Array { to.Kind() == reflect.Slice || to.Kind() == reflect.Array {
// Use ConvertSlice to convert value // Use ConvertSlice to convert value
to.Set(reflect.ValueOf(ConvertSlice( return reflect.ValueOf(ConvertSlice(
in.Interface().([]any), in.Interface().([]any),
toType, toType,
))) )), nil
} }
return to, fmt.Errorf("cannot convert %s to %s", inType, toType) return to, fmt.Errorf("cannot convert %s to %s", inType, toType)
@ -104,13 +104,12 @@ func ConvertSlice(in []any, to reflect.Type) any {
// Set output value to input value // Set output value to input value
outVal.Set(inVal) outVal.Set(inVal)
} else { } else {
// If input value can be converted to output type newVal, err := Convert(inVal, outType)
if inVal.CanConvert(outType) { if err != nil {
// Convert and set output value to input value
outVal.Set(inVal.Convert(outType))
} else {
// Set output value to its zero value // Set output value to its zero value
outVal.Set(reflect.Zero(outVal.Type())) outVal.Set(reflect.Zero(outVal.Type()))
} else {
outVal.Set(newVal)
} }
} }