-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathzero.go
65 lines (58 loc) · 1.33 KB
/
zero.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package refutil
import (
"reflect"
)
// Zeroer is like assertion with adition check
// if value can be used for type assertion to Zeroer
func (v Value) Zeroer() (Zeroer, bool) {
if !v.IsValid() {
return nil, false
}
if v.IsNil() {
return nil, false
}
z, k := v.Interface().(Zeroer)
return z, k
}
// IsZero return true if underlying type is equal to its zero value
func (v Value) IsZero() bool {
if zeroer, k := v.Zeroer(); k {
return zeroer.IsZero()
}
if v.IsNil() {
return true
}
t := v.Type()
switch t.Kind() {
case reflect.Map:
return v.Len() == 0
case reflect.Chan:
return v.Len() == 0
case reflect.Slice:
s := t.NewSlice()
return reflect.DeepEqual(v.Interface(), s.Interface())
case reflect.Ptr:
return v.Indirect().IsZero()
default:
return reflect.DeepEqual(v.Interface(), t.Zero().InterfaceOrNil())
}
}
// IsZero return true if underlying type is equal to its zero value
func (v Data) IsZero() bool {
return v.Value().IsZero()
}
// IsZero return true if underlying type is equal to its zero value
func IsZero(v interface{}) bool {
return NewData(v).IsZero()
}
// Zero will return zero of type
func (t Type) Zero() Value {
if t.IsNil() {
return NewValue(nil)
}
return NewValue(reflect.Zero(t.Type))
}
// Zero will return zero of its own type
func (v Value) Zero() Value {
return v.Type().Zero()
}