我正在尝试比较两张地图的身份
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::0x442280
and c as pointer::0x442280
似乎具有相同的值,这确实证实了我的怀疑,即这些变量以某种方式指向同一个字典。
那么有谁知道我怎样才能做到这一点b
and c
是“同一个对象”吗?
不漂亮,但你可以使用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())
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)