1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-15 02:02:27 +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

@@ -4,7 +4,9 @@
// Package pointer contains some util functions to operate go pointer. // Package pointer contains some util functions to operate go pointer.
package pointer package pointer
import "reflect" import (
"reflect"
)
// Of returns a pointer to the value `v`. // Of returns a pointer to the value `v`.
// Play: https://go.dev/play/p/HFd70x4DrMj // Play: https://go.dev/play/p/HFd70x4DrMj
@@ -47,5 +49,10 @@ func ExtractPointer(value any) any {
if t.Kind() != reflect.Pointer { if t.Kind() != reflect.Pointer {
return value return value
} }
return ExtractPointer(v.Elem().Interface())
if v.Elem().IsValid() {
return ExtractPointer(v.Elem().Interface())
}
return nil
} }

View File

@@ -52,6 +52,16 @@ func (f *Field) IsZero() bool {
return reflect.DeepEqual(z, v) 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 // Name returns the name of the given field
func (f *Field) Name() string { func (f *Field) Name() string {
return f.field.Name return f.field.Name
@@ -111,7 +121,9 @@ func (f *Field) mapValue(value any) any {
ret = v.Interface() ret = v.Interface()
} }
default: default:
ret = v.Interface() if v.Kind().String() != "invalid" {
ret = v.Interface()
}
} }
return ret 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 == "-" { if !f.IsExported() || f.tag.IsEmpty() || f.tag.Name == "-" {
continue continue
} }
if f.IsZero() && f.tag.HasOption("omitempty") { if f.IsZero() && f.tag.HasOption("omitempty") {
continue continue
} }
if f.IsNil() {
continue
}
result[f.tag.Name] = f.mapValue(f.Value()) 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) { func TestStruct_Fields(t *testing.T) {
t.Parallel() t.Parallel()