Skip to content

Commit 4247b1b

Browse files
Jillestapelberg
authored andcommitted
proto: Add CloneOf[M Message](m M) M
This allows writing: `copy := proto.CloneOf(orig)` instead of the previous: `copy := proto.Clone(orig).(*pb.MyMessage)` Fixes golang/protobuf#1594 Change-Id: I7b8b712b6e59607ccc339720ee3c146e8a7ea28b Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/653536 Reviewed-by: Cassondra Foesch <[email protected]> Reviewed-by: Michael Stapelberg <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Damien Neil <[email protected]>
1 parent f7fcf5b commit 4247b1b

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

proto/merge.go

+6
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ func Clone(m Message) Message {
5959
return dst.Interface()
6060
}
6161

62+
// CloneOf returns a deep copy of m. If the top-level message is invalid,
63+
// it returns an invalid message as well.
64+
func CloneOf[M Message](m M) M {
65+
return Clone(m).(M)
66+
}
67+
6268
// mergeOptions provides a namespace for merge functions, and can be
6369
// exported in the future if we add user-visible merge options.
6470
type mergeOptions struct{}

proto/merge_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,16 @@ func TestClone(t *testing.T) {
853853
}
854854
}
855855

856+
func TestCloneOf(t *testing.T) {
857+
want := &testpb.TestAllTypes{
858+
OptionalInt32: proto.Int32(1),
859+
}
860+
got := proto.CloneOf(want)
861+
if !proto.Equal(got, want) {
862+
t.Errorf("Clone(src) != src:\n got %v\nwant %v", got, want)
863+
}
864+
}
865+
856866
// mutateValue changes a Value, returning a new value.
857867
//
858868
// For scalar values, it returns a value different from the input.

0 commit comments

Comments
 (0)