Search code examples
gogo-map

How to know if 2 go maps reference the same data


Go maps are references to internal data. Meaning that when a map is "copied", they end up sharing the same reference and thus editing the same data. This is something highly different than having another map with the same items. However, I cannot find any way to tell the difference between both cases.

import "fmt"
import "reflect"

func main() {
    a := map[string]string{"a": "a", "b": "b"}
    // b references the same data as a
    b := a
    // thus editing b also edits a
    b["c"] = "c"
    // c is a different map, but with same items
    c := map[string]string{"a": "a", "b": "b", "c": "c"}

    reflect.DeepEqual(a, b) // true
    reflect.DeepEqual(a, c) // true too
    a == b // illegal
    a == c // illegal too
    &a == &b // false
    &a == &c // false too
    *a == *b // illegal
    *a == *c // illegal too
}

Any solution for that ?


Solution

  • Use the reflect package to compare the maps as pointers:

    func same(x, y interface{}) bool {
        return reflect.ValueOf(x).Pointer() == reflect.ValueOf(y).Pointer()
    }
    

    Use it like this on the maps in the question:

    fmt.Println(same(a, b)) // prints true
    fmt.Println(same(a, c)) // prints false