如何比较地图的身份或此示例中发生的情况?

时间:2018-10-25 13:33:59

标签: dictionary go identity

我正在尝试比较2张地图的身份

package main

import "fmt"

func main() {
    a := map[int]map[int]int{1:{2:2}}

    b := a[1]
    c := a[1]

    // I can't do this: 
    // if b == c
    // because I get: 
    // invalid operation: b == c (map can only be compared to nil)

    // but as far as I can tell, mutation works, meaning that the 2 maps might actually be identical
    b[3] = 3

    fmt.Println(c[3]) // so mutation works...


    fmt.Printf("b as pointer::%p\n", b)
    fmt.Printf("c as pointer::%p\n", c) 

    // ok, so maybe these are the pointers to the variables b and c... but still, those variables contain the references to the same map, so it's understandable that these are different, but then I can't compare b==c like this
    fmt.Printf("&b::%p\n", &b)
    fmt.Printf("&c::%p\n", &c)  

    fmt.Println(&b == &c)
}

这将产生以下输出:

3
b as pointer::0x442280
c as pointer::0x442280
&b::0x40e130
&c::0x40e138
false

令我特别困惑的是,尽管b as pointer::0x442280c as pointer::0x442280似乎具有相同的值,这确实使我怀疑我怀疑那些变量在某种程度上指向相同的格言。

那么有谁知道我该怎么做才能说bc是“同一对象”?

2 个答案:

答案 0 :(得分:2)

不漂亮,但您可以使用reflect.ValueOf(b).Pointer()

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := map[int]map[int]int{1: {2: 2}}

    b := a[1]
    c := a[1]

    d := map[int]int{2: 2}

    fmt.Println(reflect.ValueOf(b).Pointer() == reflect.ValueOf(c).Pointer())
    fmt.Println(reflect.ValueOf(c).Pointer() == reflect.ValueOf(d).Pointer())
}

答案 1 :(得分:0)

好吧,所以我显然是该语言的新手,并且我不会很快批评它,但这是我找到的解决方案:

Python代码:

obj1 is obj2

JavaScript代码:

obj1 === obj2  // for objects, which is what I care about

Java代码:

obj1 == obj2

然后是代码:

fmt.Sprintf("%p", obj1) == fmt.Sprintf("%p", obj2)

是的,它的样子就是这样:我得到了指向2个变量的指针的字符串表示形式,并进行比较。字符串看起来像这样0x442280

fmt.DeepEqual不是我的解决方案,因为

  1. 它检查指针是否相等,然后
  2. 然后检查地图中的值是否相等

这完全不是我想要的。我只想知道地图是否是完全相同的对象,而不是它们是否包含相同的值