-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ca8e127
commit 8152032
Showing
2 changed files
with
31 additions
and
0 deletions.
There are no files selected for viewing
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
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") |
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
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()) | ||
} |