-
Notifications
You must be signed in to change notification settings - Fork 702
/
reflect.go
51 lines (44 loc) · 1.32 KB
/
reflect.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
package xreflect
import (
"reflect"
"github.com/pkg/errors"
)
// In test if key in map or value in slice/array
func In(value interface{}, container interface{}) bool {
containerValue := reflect.ValueOf(container)
switch reflect.TypeOf(container).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < containerValue.Len(); i++ {
if containerValue.Index(i).Interface() == value {
return true
}
}
case reflect.Map:
if containerValue.MapIndex(reflect.ValueOf(value)).IsValid() {
return true
}
default:
return false
}
return false
}
// Override try override the fields of left object with right object's
func Override(left interface{}, right interface{}) error {
if reflect.ValueOf(left).IsNil() || reflect.ValueOf(right).IsNil() {
return errors.New("nil arg")
}
if reflect.ValueOf(left).Type().Kind() != reflect.Ptr ||
reflect.ValueOf(right).Type().Kind() != reflect.Ptr ||
reflect.ValueOf(left).Kind() != reflect.ValueOf(right).Kind() {
return errors.New("must be a pointer and have same type")
}
oldVal := reflect.ValueOf(left).Elem()
newVal := reflect.ValueOf(right).Elem()
for i := 0; i < oldVal.NumField(); i++ {
val := newVal.Field(i).Interface()
if !reflect.DeepEqual(val, reflect.Zero(reflect.TypeOf(val)).Interface()) {
oldVal.Field(i).Set(reflect.ValueOf(val))
}
}
return nil
}