如何知道两个 go 地图是否引用相同的数据

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

}

有什么解决办法吗?


汪汪一只猫
浏览 58回答 1
1回答

PIPIONE

使用 Reflect 包将映射作为指针进行比较:func same(x, y interface{}) bool {    return reflect.ValueOf(x).Pointer() == reflect.ValueOf(y).Pointer()}在问题中的地图上像这样使用它:fmt.Println(same(a, b)) // prints truefmt.Println(same(a, c)) // prints false
打开App,查看更多内容
随时随地看视频慕课网APP