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 })