mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-10 09:11:55 +00:00
30 lines
925 B
Go
30 lines
925 B
Go
package dynamic
|
|
|
|
import "reflect"
|
|
|
|
// MergeStructValues merges the field value from the source struct to the dest struct.
|
|
// Only fields with the same type and the same name will be updated.
|
|
func MergeStructValues(dst, src interface{}) {
|
|
rtA := reflect.TypeOf(dst)
|
|
srcStructType := reflect.TypeOf(src)
|
|
|
|
rtA = rtA.Elem()
|
|
srcStructType = srcStructType.Elem()
|
|
|
|
for i := 0; i < rtA.NumField(); i++ {
|
|
fieldType := rtA.Field(i)
|
|
fieldName := fieldType.Name
|
|
// if there is a field with the same name
|
|
if fieldSrcType, ok := srcStructType.FieldByName(fieldName); ok {
|
|
// ensure that the type is the same
|
|
if fieldSrcType.Type == fieldType.Type {
|
|
srcValue := reflect.ValueOf(src).Elem().FieldByName(fieldName)
|
|
dstValue := reflect.ValueOf(dst).Elem().FieldByName(fieldName)
|
|
if (fieldType.Type.Kind() == reflect.Ptr && dstValue.IsNil()) || dstValue.IsZero() {
|
|
dstValue.Set(srcValue)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|