mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 08:32:40 +08:00
isZero
This commit is contained in:
@ -41,9 +41,7 @@ func DeepCopy() optionFunc {
|
||||
}
|
||||
|
||||
func SkipField(field string) optionFunc {
|
||||
return func(o *option) {
|
||||
o.SkipFields = append(o.SkipFields, field)
|
||||
}
|
||||
return SkipFields([]string{field})
|
||||
}
|
||||
|
||||
func SkipFields(fields []string) optionFunc {
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/charlienet/go-mixed/structs"
|
||||
"github.com/go-playground/assert/v2"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
@ -19,3 +19,22 @@ func TestNew(t *testing.T) {
|
||||
t.Log(s.Names())
|
||||
t.Log(s.Values())
|
||||
}
|
||||
|
||||
func TestIsZero(t *testing.T) {
|
||||
var v1 int
|
||||
assert.True(t, structs.IsZero(v1))
|
||||
|
||||
var v2 = struct {
|
||||
Msg string
|
||||
}{}
|
||||
assert.True(t, structs.IsZero(v2))
|
||||
|
||||
var v3 = struct {
|
||||
VV int
|
||||
Msg string
|
||||
}{Msg: "abc"}
|
||||
assert.False(t, structs.IsZero(v3))
|
||||
|
||||
v3.Msg = ""
|
||||
assert.True(t, structs.IsZero(v3))
|
||||
}
|
||||
|
@ -53,6 +53,17 @@ func (s *Struct) Values() []any {
|
||||
return values
|
||||
}
|
||||
|
||||
func (s *Struct) IsZero() bool {
|
||||
for _, fi := range s.fields {
|
||||
source := s.value.FieldByName(fi.name)
|
||||
if !source.IsZero() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Struct) ToMap() map[string]any {
|
||||
m := make(map[string]any, len(s.fields))
|
||||
for _, fi := range s.fields {
|
||||
@ -112,6 +123,16 @@ func Map2Struct(o map[string]any, dst any) {
|
||||
|
||||
}
|
||||
|
||||
func IsZero(o any) bool {
|
||||
v := reflect.ValueOf(o)
|
||||
if v.IsZero() {
|
||||
return true
|
||||
}
|
||||
|
||||
s := New(o)
|
||||
return s.IsZero()
|
||||
}
|
||||
|
||||
func Struct2Map(o any, opts ...optionFunc) map[string]any {
|
||||
return New(o, opts...).ToMap()
|
||||
}
|
||||
|
Reference in New Issue
Block a user