Go 映射是对内部数据的引用。这意味着当“复制”地图时,它们最终会共享相同的参考并因此编辑相同的数据。这与使用具有相同项目的另一张地图大不相同。但是,我找不到任何方法来区分这两种情况。
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
}
Run Code Online (Sandbox Code Playgroud)
有什么解决办法吗?
使用反射包将地图作为指针进行比较:
func same(x, y interface{}) bool {
return reflect.ValueOf(x).Pointer() == reflect.ValueOf(y).Pointer()
}
Run Code Online (Sandbox Code Playgroud)
在问题中的地图上像这样使用它:
fmt.Println(same(a, b)) // prints true
fmt.Println(same(a, c)) // prints false
Run Code Online (Sandbox Code Playgroud)