From 5400d22bc2e3afe2391a7400f7d64d8eb722758a Mon Sep 17 00:00:00 2001 From: viken Date: Sat, 12 Dec 2020 21:57:07 +0800 Subject: [PATCH] improve function empty --- internal/empty/empty.go | 29 ++++++++++++++++++++++++++++- internal/empty/empty_test.go | 27 +++++++++++++++++++++++---- 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/internal/empty/empty.go b/internal/empty/empty.go index 19aa3a7de..4c517606a 100644 --- a/internal/empty/empty.go +++ b/internal/empty/empty.go @@ -104,13 +104,40 @@ func IsEmpty(value interface{}) bool { } else { rv = reflect.ValueOf(value) } + switch rv.Kind() { + case reflect.Bool: + return !rv.Bool() + case reflect.Int, + reflect.Int8, + reflect.Int16, + reflect.Int32, + reflect.Int64: + return rv.Int() == 0 + case reflect.Uint, + reflect.Uint8, + reflect.Uint16, + reflect.Uint32, + reflect.Uint64, + reflect.Uintptr: + return rv.Uint() == 0 + case reflect.Float32, + reflect.Float64: + return rv.Float() == 0 + case reflect.String: + return rv.Len() == 0 + case reflect.Struct: + for i := 0; i < rv.NumField(); i++ { + if !IsEmpty(rv) { + return false + } + } + return true case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array: return rv.Len() == 0 - case reflect.Func, reflect.Ptr, reflect.Interface, diff --git a/internal/empty/empty_test.go b/internal/empty/empty_test.go index c7ab9be63..520aa64ee 100644 --- a/internal/empty/empty_test.go +++ b/internal/empty/empty_test.go @@ -15,6 +15,10 @@ import ( "github.com/gogf/gf/util/gconv" ) +type TestInt int + +type TestString string + type TestPerson interface { Say() string } @@ -31,16 +35,26 @@ func TestIsEmpty(t *testing.T) { tmpT2 := func() {} tmpT2 = nil tmpT3 := make(chan int, 0) - var tmpT4 TestPerson = nil - var tmpT5 *TestPerson = nil + var ( + tmpT4 TestPerson = nil + tmpT5 *TestPerson = nil + tmpT6 TestPerson = TestWoman{} + tmpT7 TestInt = 0 + tmpT8 TestString = "" + ) tmpF1 := "1" tmpF2 := func(a string) string { return "1" } tmpF3 := make(chan int, 1) tmpF3 <- 1 - var tmpF4 TestPerson = TestWoman{} - tmpF5 := &tmpF4 + var ( + tmpF4 TestPerson = &TestWoman{} + tmpF5 TestInt = 1 + tmpF6 TestString = "1" + ) + // true t.Assert(empty.IsEmpty(nil), true) + t.Assert(empty.IsEmpty(0), true) t.Assert(empty.IsEmpty(gconv.Int(tmpT1)), true) t.Assert(empty.IsEmpty(gconv.Int8(tmpT1)), true) t.Assert(empty.IsEmpty(gconv.Int16(tmpT1)), true) @@ -64,6 +78,10 @@ func TestIsEmpty(t *testing.T) { t.Assert(empty.IsEmpty(tmpT3), true) t.Assert(empty.IsEmpty(tmpT4), true) t.Assert(empty.IsEmpty(tmpT5), true) + t.Assert(empty.IsEmpty(tmpT6), true) + t.Assert(empty.IsEmpty(tmpT7), true) + t.Assert(empty.IsEmpty(tmpT8), true) + // false t.Assert(empty.IsEmpty(gconv.Int(tmpF1)), false) t.Assert(empty.IsEmpty(gconv.Int8(tmpF1)), false) @@ -87,5 +105,6 @@ func TestIsEmpty(t *testing.T) { t.Assert(empty.IsEmpty(tmpF3), false) t.Assert(empty.IsEmpty(tmpF4), false) t.Assert(empty.IsEmpty(tmpF5), false) + t.Assert(empty.IsEmpty(tmpF6), false) }) }