1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

fix: fix issue #162

This commit is contained in:
dudaodong
2024-01-29 11:00:50 +08:00
parent a630a7cda9
commit 38920e3be6
4 changed files with 67 additions and 3 deletions

View File

@@ -52,6 +52,16 @@ func (f *Field) IsZero() bool {
return reflect.DeepEqual(z, v)
}
// IsNil returns true if the given field is nil value.
func (f *Field) IsNil() bool {
v := f.Value()
if v == nil || (reflect.ValueOf(v)).Kind() == reflect.Ptr && reflect.ValueOf(v).IsNil() {
return true
}
return false
}
// Name returns the name of the given field
func (f *Field) Name() string {
return f.field.Name
@@ -111,7 +121,9 @@ func (f *Field) mapValue(value any) any {
ret = v.Interface()
}
default:
ret = v.Interface()
if v.Kind().String() != "invalid" {
ret = v.Interface()
}
}
return ret
}

View File

@@ -71,9 +71,15 @@ func (s *Struct) ToMap() (map[string]any, error) {
if !f.IsExported() || f.tag.IsEmpty() || f.tag.Name == "-" {
continue
}
if f.IsZero() && f.tag.HasOption("omitempty") {
continue
}
if f.IsNil() {
continue
}
result[f.tag.Name] = f.mapValue(f.Value())
}

View File

@@ -65,6 +65,45 @@ func TestStruct_ToMap(t *testing.T) {
})
}
func Test_ToMap2(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestStruct_ToMap")
type M struct {
Name string `json:"name"`
}
type S struct {
ID int `json:"id"`
M *M `json:"m"`
}
s1 := &S{
ID: 1,
}
var expect1 = map[string]any{"id": 1}
map1, err := ToMap(s1)
assert.IsNil(err)
assert.Equal(expect1, map1)
s2 := &S{
ID: 1,
M: &M{
Name: "test",
},
}
var expect2 = map[string]any{
"id": 1,
"m": map[string]any{
"name": "test",
}}
map2, err := ToMap(s2)
assert.IsNil(err)
assert.Equal(expect2, map2)
}
func TestStruct_Fields(t *testing.T) {
t.Parallel()