Skip to content

Commit 79cabaa

Browse files
hopehookIan Lance Taylor
authored andcommitted
maps: make Clone preserve nil map
The x/exp/maps.Clone function doesn't preserve nil the way x/exp/slices.Clone does, but it should be. Fixes golang/go#53817 Change-Id: Ib1867fb6e31d990d8b8a846e9dba8a5b6ba83c48 Reviewed-on: https://go-review.googlesource.com/c/exp/+/417274 Reviewed-by: Dmitri Shuralyov <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]>
1 parent b4a6d95 commit 79cabaa

File tree

2 files changed

+12
-0
lines changed

2 files changed

+12
-0
lines changed

maps/maps.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ func Clear[M ~map[K]V, K comparable, V any](m M) {
6363
// Clone returns a copy of m. This is a shallow clone:
6464
// the new keys and values are set using ordinary assignment.
6565
func Clone[M ~map[K]V, K comparable, V any](m M) M {
66+
// Preserve nil in case it matters.
67+
if m == nil {
68+
return nil
69+
}
6670
r := make(M, len(m))
6771
for k, v := range m {
6872
r[k] = v

maps/maps_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,14 @@ func TestClone(t *testing.T) {
142142
}
143143
}
144144

145+
func TestCloneNil(t *testing.T) {
146+
var m1 map[string]int
147+
mc := Clone(m1)
148+
if mc != nil {
149+
t.Errorf("Clone(%v) = %v, want %v", m1, mc, m1)
150+
}
151+
}
152+
145153
func TestCopy(t *testing.T) {
146154
mc := Clone(m1)
147155
Copy(mc, mc)

0 commit comments

Comments
 (0)