Created
October 20, 2023 02:07
-
-
Save huantt/8e96119ffae55f10a68fe6c8dc7212d9 to your computer and use it in GitHub Desktop.
Merge Golang Models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(¤tRecord).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