Skip to content

Commit

Permalink
track
Browse files Browse the repository at this point in the history
  • Loading branch information
garrettladley committed May 29, 2024
1 parent ca8e127 commit 8152032
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions backend/errs/validate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package errs

import "errors"

var ErrAtLeastOne = errors.New("at least one field must be provided")
26 changes: 26 additions & 0 deletions backend/utilities/merge.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package utilities

import "reflect"

// Merge merges two structs of the same type such that non-zero values from the updated struct take precedence.
func Merge[T any](existing T, updated T) T {
existingVal := reflect.ValueOf(&existing).Elem()
updatedVal := reflect.ValueOf(updated)

for i := 0; i < existingVal.NumField(); i++ {
existingField := existingVal.Field(i)
updatedField := updatedVal.Field(i)

// Check if the updated field is non-zero
if !isZeroValue(updatedField) {
existingField.Set(updatedField)
}
}

return existing
}

// isZeroValue checks if a reflect.Value is the zero value for its type
func isZeroValue(v reflect.Value) bool {
return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface())
}

0 comments on commit 8152032

Please sign in to comment.