goext/dataext/merge.go

36 lines
623 B
Go
Raw Permalink Normal View History

2022-11-19 16:26:45 +01:00
package dataext
import (
"reflect"
)
func ObjectMerge[T1 any, T2 any](base T1, override T2) T1 {
reflBase := reflect.ValueOf(&base).Elem()
reflOvrd := reflect.ValueOf(&override).Elem()
for i := 0; i < reflBase.NumField(); i++ {
fieldBase := reflBase.Field(i)
fieldOvrd := reflOvrd.Field(i)
if fieldBase.Kind() != reflect.Ptr || fieldOvrd.Kind() != reflect.Ptr {
continue
}
kindBase := fieldBase.Type().Elem().Kind()
kindOvrd := fieldOvrd.Type().Elem().Kind()
if kindBase != kindOvrd {
continue
}
if !fieldOvrd.IsNil() {
fieldBase.Set(fieldOvrd.Elem().Addr())
}
}
return base
}