From d8bfa04613ae87e6ecce254509452bc3f2ad3cb6 Mon Sep 17 00:00:00 2001 From: Nate Armstrong Date: Mon, 6 May 2024 13:59:38 -0700 Subject: [PATCH] Make copy generic over map types --- util/maputil/maputil.go | 4 ++-- util/maputil/maputil_test.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/util/maputil/maputil.go b/util/maputil/maputil.go index ec5ecad..4631d9b 100644 --- a/util/maputil/maputil.go +++ b/util/maputil/maputil.go @@ -75,8 +75,8 @@ func Add(m map[string]interface{}, nameValuePairs ...interface{}) map[string]int } // Copy creates a shallow copy of the given map. -func Copy(m map[string]interface{}) map[string]interface{} { - cp := make(map[string]interface{}, len(m)) +func Copy[K comparable, T any](m map[K]T) map[K]T { + cp := make(map[K]T, len(m)) for k, v := range m { cp[k] = v } diff --git a/util/maputil/maputil_test.go b/util/maputil/maputil_test.go index 950fddd..3e90bfe 100644 --- a/util/maputil/maputil_test.go +++ b/util/maputil/maputil_test.go @@ -192,3 +192,21 @@ func TestCopyMSI(t *testing.T) { require.Equal(t, ma2["one"], ma["one"]) require.Equal(t, ma2["two"], ma["two"]) } + +func TestCopyGeneric(t *testing.T) { + msi := map[string]interface{}{ + "un": 1, + "deux": "two", + } + m2 := Copy(msi) + require.Equal(t, msi, m2) + + mis := map[int]string{ + 1: "one", + 2: "two", + } + var m3 map[int]string + m3 = Copy(mis) + require.Equal(t, mis, m3) + +}