-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace.go
32 lines (30 loc) · 965 Bytes
/
replace.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
package replace
import (
"reflect"
)
// Replace replace struct value by another struct
func Replace(old, new interface{}) {
if reflect.ValueOf(old).Kind() != reflect.Ptr {
panic("old must be a pointer to a struct")
}
if reflect.ValueOf(new).Kind() != reflect.Ptr {
panic("new must be a pointer to a struct")
}
if reflect.ValueOf(old).Elem().Kind() != reflect.Struct {
panic("old must be a pointer to a struct")
}
if reflect.ValueOf(new).Elem().Kind() != reflect.Struct {
panic("new must be a pointer to a struct")
}
oldReflect := reflect.ValueOf(old).Elem()
oldField := reflect.TypeOf(old).Elem()
newField := reflect.TypeOf(new).Elem()
newReflect := reflect.ValueOf(new).Elem()
for i, n := 0, newField.NumField(); i < n; i++ {
name := newField.Field(i).Name
_, oldHave := oldField.FieldByName(name)
if oldHave && !newReflect.FieldByName(name).IsNil() {
oldReflect.FieldByName(name).Set(newReflect.FieldByName(name).Elem())
}
}
}