-
Notifications
You must be signed in to change notification settings - Fork 0
/
typecheck.go
49 lines (45 loc) · 942 Bytes
/
typecheck.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
package polykit
import (
"fmt"
"reflect"
)
func IsNil(v interface{}) bool {
if v == nil {
return true
}
value := reflect.ValueOf(v)
switch value.Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Func, reflect.Slice, reflect.Interface:
return value.IsNil()
default:
return false
}
}
func IsEmpty(v interface{}) bool {
if v == nil {
return true
}
value := reflect.ValueOf(v)
switch value.Kind() {
case reflect.Array, reflect.String, reflect.Slice, reflect.Map:
return value.Len() == 0
case reflect.Ptr:
if IsNil(v) {
return true
}
return IsEmpty(value.Elem().Interface())
case reflect.Struct:
for i := 0; i < value.NumField(); i++ {
if !IsEmpty(value.Field(i).Interface()) {
return false
}
}
}
return false
}
func ErrIfNotNil(v interface{}, message string) error {
if !IsNil(v) {
return fmt.Errorf("invalid value: %s, error: %v", v, message)
}
return nil
}