Skip to content

Commit

Permalink
allow a custom map type to declare DeepCopy func (#88)
Browse files Browse the repository at this point in the history
Signed-off-by: Nicolas De Loof <[email protected]>
  • Loading branch information
ndeloof authored Jun 21, 2024
1 parent dcab42e commit 0a721d5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
12 changes: 10 additions & 2 deletions plugin/deepcopy/deepcopy.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,10 @@ func (g *gen) genField(fieldType types.Type, thisField, thatField string) error
p.P("%s = make(%s, len(%s))", thatField, g.TypeString(typ), thisField)
p.Out()
p.P("}") // not nil
if canCopy(typ.Elem()) {
named, isNamed := fieldType.(*types.Named)
if isNamed && hasDeepCopyMethod(named) {
p.P("%s.DeepCopy(%s)", wrap(thisField), thatField)
} else if canCopy(typ.Elem()) {
p.P("copy(%s, %s)", thatField, thisField)
} else {
p.P("%s(%s, %s)", g.GetFuncName(typ), thatField, thisField)
Expand All @@ -381,7 +384,12 @@ func (g *gen) genField(fieldType types.Type, thisField, thatField string) error
p.P("if %s != nil {", thisField)
p.In()
p.P("%s = make(%s, len(%s))", thatField, g.TypeString(typ), thisField)
p.P("%s(%s, %s)", g.GetFuncName(typ), thatField, thisField)
named, isNamed := fieldType.(*types.Named)
if isNamed && hasDeepCopyMethod(named) {
p.P("%s.DeepCopy(%s)", wrap(thisField), thatField)
} else {
p.P("%s(%s, %s)", g.GetFuncName(typ), thatField, thisField)
}
p.Out()
p.P("} else {")
p.In()
Expand Down
19 changes: 19 additions & 0 deletions test/normal/deepcopy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,22 @@ func TestDeepCopyMapNilEntry(t *testing.T) {
t.Fatalf("want %v got %v\n this = %#v, that = %#v\n", want, got, this, that)
}
}

func TestDeepCopyCustomMap(t *testing.T) {
this := customMap{
"a": "A",
}
that := customMap{}
deepcopy(this, that)
if that["a"] != "copy of A" {
t.Fatalf("expected use of customMap.DeepCopy")
}
}

type customMap map[string]string

func (c customMap) DeepCopy(to customMap) {
for k, v := range c {
to[k] = "copy of " + v
}
}

0 comments on commit 0a721d5

Please sign in to comment.