Skip to content

Instantly share code, notes, and snippets.

@huantt
Created October 20, 2023 02:07
Show Gist options
  • Save huantt/8e96119ffae55f10a68fe6c8dc7212d9 to your computer and use it in GitHub Desktop.
Save huantt/8e96119ffae55f10a68fe6c8dc7212d9 to your computer and use it in GitHub Desktop.
Merge Golang Models
// MergeRecord
// if currentRecord.Field exists -> uses currentRecord.Field
// if currentRecord.Field exists AND newRecord.Field exists -> uses currentRecord.Field
// if currentRecord.Field does not exist AND newRecord.Field exists -> uses newRecord.Field
func MergeRecord[M any](currentRecord M, newRecord M) M {
currentValue := reflect.ValueOf(&currentRecord).Elem()
newValue := reflect.ValueOf(&newRecord).Elem()
for i := 0; i < currentValue.NumField(); i++ {
currentField := currentValue.Field(i)
newField := newValue.Field(i)
if currentField.IsZero() || (currentField.Kind() == reflect.Ptr && currentField.IsNil()) {
if !newField.IsZero() || (newField.Kind() == reflect.Ptr && !newField.IsNil()) {
if currentField.CanSet() {
currentField.Set(newField)
}
}
}
}
return currentRecord
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment