How to copy a map?

后端 未结 5 738
傲寒
傲寒 2020-12-05 01:36

I\'m trying to copy the contents of a map ( amap ) inside another one (aSuperMap) and then clear amap so that it can take new values

5条回答
  •  再見小時候
    2020-12-05 02:05

    I'd use recursion just in case so you can deep copy the map and avoid bad surprises in case you were to change a map element that is a map itself.

    Here's an example in a utils.go:

    package utils
    
    func CopyMap(m map[string]interface{}) map[string]interface{} {
        cp := make(map[string]interface{})
        for k, v := range m {
            vm, ok := v.(map[string]interface{})
            if ok {
                cp[k] = CopyMap(vm)
            } else {
                cp[k] = v
            }
        }
    
        return cp
    }
    

    And its test file (i.e. utils_test.go):

    package utils
    
    import (
        "testing"
    
        "github.com/stretchr/testify/require"
    )
    
    func TestCopyMap(t *testing.T) {
        m1 := map[string]interface{}{
            "a": "bbb",
            "b": map[string]interface{}{
                "c": 123,
            },
        }
    
        m2 := CopyMap(m1)
    
        m1["a"] = "zzz"
        delete(m1, "b")
    
        require.Equal(t, map[string]interface{}{"a": "zzz"}, m1)
        require.Equal(t, map[string]interface{}{
            "a": "bbb",
            "b": map[string]interface{}{
                "c": 123,
            },
        }, m2)
    }
    

    It should easy enough to adapt if you need the map key to be something else instead of a string.

提交回复
热议问题