Skip to content

Commit d8f7ec9

Browse files
author
Rocco Ciccone
committed
feat: ptr -> zero value and zero value -> ptr overrides now work
1 parent 9e103f7 commit d8f7ec9

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

copier.go

+4
Original file line numberDiff line numberDiff line change
@@ -593,6 +593,9 @@ func set(to, from reflect.Value, deepCopy bool, converters map[converterPair]Typ
593593
}
594594
// allocate new `to` variable with default value (eg. *string -> new(string))
595595
to.Set(reflect.New(to.Type().Elem()))
596+
} else if from.Kind() != reflect.Ptr && from.IsZero() {
597+
to.Set(reflect.Zero(to.Type()))
598+
return true, nil
596599
}
597600
// depointer `to`
598601
to = to.Elem()
@@ -607,6 +610,7 @@ func set(to, from reflect.Value, deepCopy bool, converters map[converterPair]Typ
607610
}
608611
}
609612
if from.Kind() == reflect.Ptr && from.IsNil() {
613+
to.Set(reflect.Zero(to.Type()))
610614
return true, nil
611615
}
612616
if _, ok := to.Addr().Interface().(sql.Scanner); !ok && (toKind == reflect.Struct || toKind == reflect.Map || toKind == reflect.Slice) {

copier_tags_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,29 @@ func TestCopyTagOverrideZeroValue(t *testing.T) {
6060
}
6161
}
6262

63+
func TestCopyTagOverridePtrToZeroValue(t *testing.T) {
64+
options := copier.Option{IgnoreEmpty: true}
65+
address := "21 Jump Street"
66+
user1 := User1{ID: 100, Address: ""}
67+
user2 := User2{DOB: "1 November, 1970", Address: &address, ID: 12345}
68+
69+
copier.CopyWithOption(&user2, user1, options)
70+
if user2.Address != nil {
71+
t.Error("Original Address was not overwritten")
72+
}
73+
}
74+
75+
func TestCopyTagOverrideZeroValueToPtr(t *testing.T) {
76+
options := copier.Option{IgnoreEmpty: true}
77+
user1 := User2{DOB: "1 November, 1970", Address: nil, ID: 12345}
78+
user2 := User1{ID: 100, Address: "1 November, 1970"}
79+
80+
copier.CopyWithOption(&user2, user1, options)
81+
if user1.Address != nil {
82+
t.Error("Original Address was not overwritten")
83+
}
84+
}
85+
6386
func TestCopyTagOverridePtr(t *testing.T) {
6487
options := copier.Option{IgnoreEmpty: true}
6588
address := "21 Jump Street"

0 commit comments

Comments
 (0)