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}有什么解決辦法嗎?
1 回答

PIPIONE
TA貢獻1829條經驗 獲得超9個贊
使用 Reflect 包將映射作為指針進行比較:
func same(x, y interface{}) bool {
return reflect.ValueOf(x).Pointer() == reflect.ValueOf(y).Pointer()
}
在問題中的地圖上像這樣使用它:
fmt.Println(same(a, b)) // prints true
fmt.Println(same(a, c)) // prints false
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報
0/150
提交
取消