Skip to content

Commit 4acc1c1

Browse files
committed
copy interface
1 parent 491d360 commit 4acc1c1

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

deepcopy.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ import (
1111
"time"
1212
)
1313

14+
// Interface for delegating copy process to type
15+
type Interface interface {
16+
DeepCopy() interface{}
17+
}
18+
1419
// Iface is an alias to Copy; this exists for backwards compatibility reasons.
1520
func Iface(iface interface{}) interface{} {
1621
return Copy(iface)
@@ -40,6 +45,14 @@ func Copy(src interface{}) interface{} {
4045
// copyRecursive does the actual copying of the interface. It currently has
4146
// limited support for what it can handle. Add as needed.
4247
func copyRecursive(original, cpy reflect.Value) {
48+
// check for implement deepcopy.Interface
49+
if original.CanInterface() {
50+
if copier, ok := original.Interface().(Interface); ok {
51+
cpy.Set(reflect.ValueOf(copier.DeepCopy()))
52+
return
53+
}
54+
}
55+
4356
// handle according to original's Kind
4457
switch original.Kind() {
4558
case reflect.Ptr:

deepcopy_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1082,3 +1082,29 @@ func TestIssue9(t *testing.T) {
10821082
}
10831083
}
10841084
}
1085+
1086+
type I struct {
1087+
A string
1088+
}
1089+
1090+
func (i *I) DeepCopy() interface{} {
1091+
return &I{A: "custom copy"}
1092+
}
1093+
1094+
type NestI struct {
1095+
I *I
1096+
}
1097+
1098+
func TestInterface(t *testing.T) {
1099+
i := &I{A: "A"}
1100+
copied := Copy(i).(*I)
1101+
if copied.A != "custom copy" {
1102+
t.Errorf("expected value %v, but it's %v", "custom copy", copied.A)
1103+
}
1104+
// check for nesting values
1105+
ni := &NestI{I: &I{A: "A"}}
1106+
copiedNest := Copy(ni).(*NestI)
1107+
if copiedNest.I.A != "custom copy" {
1108+
t.Errorf("expected value %v, but it's %v", "custom copy", copiedNest.I.A)
1109+
}
1110+
}

0 commit comments

Comments
 (0)