Skip to content

Commit

Permalink
fix issue in SliceMap/Maps for package gconv when nil value in ma…
Browse files Browse the repository at this point in the history
…p of slice item (#2857)
  • Loading branch information
gqcn authored Aug 10, 2023
1 parent 243fe73 commit 4020eb9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
16 changes: 11 additions & 5 deletions util/gconv/gconv_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
17 changes: 17 additions & 0 deletions util/gconv/gconv_z_unit_slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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))
})
}

0 comments on commit 4020eb9

Please sign in to comment.