fix issue in SliceMap/Maps for package gconv when nil value in map of slice item (#2857)

This commit is contained in:
John Guo
2023-08-10 21:59:21 +08:00
committed by GitHub
parent 243fe73c57
commit 4020eb9b4c
2 changed files with 28 additions and 5 deletions

View File

@ -259,11 +259,17 @@ func doMapConvertForMapOrStructValue(in doMapConvertForMapOrStructValueInput) in
mapKeyValue = reflectValue.MapIndex(k)
mapValue interface{}
)
if mapKeyValue.IsZero() {
// in case of:
// exception recovered: reflect: call of reflect.Value.Interface on zero Value
mapValue = reflect.New(mapKeyValue.Type()).Elem()
} else {
switch {
case mapKeyValue.IsZero():
if mapKeyValue.IsNil() {
// quick check for nil value.
mapValue = nil
} else {
// in case of:
// exception recovered: reflect: call of reflect.Value.Interface on zero Value
mapValue = reflect.New(mapKeyValue.Type()).Elem().Interface()
}
default:
mapValue = mapKeyValue.Interface()
}
dataMap[String(k.Interface())] = doMapConvertForMapOrStructValue(

View File

@ -10,6 +10,8 @@ import (
"testing"
"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/encoding/gjson"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/test/gtest"
"github.com/gogf/gf/v2/util/gconv"
@ -457,3 +459,18 @@ func Test_EmptyString_To_CustomType(t *testing.T) {
t.Assert(len(req.Types), 0)
})
}
func Test_SliceMap_WithNilMapValue(t *testing.T) {
gtest.C(t, func(t *gtest.T) {
var (
list1 = []gdb.Record{
{"name": nil},
}
list2 []map[string]any
)
list2 = gconv.SliceMap(list1)
t.Assert(len(list2), 1)
t.Assert(list1[0], list2[0])
t.Assert(gjson.MustEncodeString(list1), gjson.MustEncodeString(list2))
})
}