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.

Revisions

  1. huantt created this gist Oct 20, 2023.
    23 changes: 23 additions & 0 deletions merge-go-models.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    // 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
    }