Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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))
})
}