improve function empty

This commit is contained in:
viken 2020-12-12 21:57:07 +08:00
parent 8d3fd21be5
commit 5400d22bc2
2 changed files with 51 additions and 5 deletions

View File

@ -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,

View File

@ -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)
})
}