From f19b84e8502c261fdfb448404ea0543c37095828 Mon Sep 17 00:00:00 2001 From: Salim Afiune Maya Date: Tue, 22 Apr 2025 14:55:11 -0700 Subject: [PATCH] maps: handle copy with nil maps By default, `range` will cover the case where `src` is `nil`, but if `dst` is `nil`, then `Copy` will throw a panic like: ``` panic: assignment to entry in nil map ``` Signed-off-by: Salim Afiune Maya --- src/maps/maps.go | 3 +++ src/maps/maps_test.go | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/src/maps/maps.go b/src/maps/maps.go index b712dd3fe8ebaa..746a5afda923fa 100644 --- a/src/maps/maps.go +++ b/src/maps/maps.go @@ -60,6 +60,9 @@ func Clone[M ~map[K]V, K comparable, V any](m M) M { // the value in dst will be overwritten by the value associated // with the key in src. func Copy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2) { + if dst == nil { + dst = make(map[K]V) + } for k, v := range src { dst[k] = v } diff --git a/src/maps/maps_test.go b/src/maps/maps_test.go index c8ee3cd0311f5f..c55f04fab2853c 100644 --- a/src/maps/maps_test.go +++ b/src/maps/maps_test.go @@ -121,6 +121,15 @@ func TestCopy(t *testing.T) { Copy(make(M1), make(M2)) } +func TestCopyNil(t *testing.T) { + var mnil map[string]int + mc := Copy(mnil, m1) + want := m1 + if !Equal(mc, want) { + t.Errorf("Copy result = %v, want %v", mc, want) + } +} + func TestDeleteFunc(t *testing.T) { mc := Clone(m1) DeleteFunc(mc, func(int, int) bool { return false })