mergo icon indicating copy to clipboard operation
mergo copied to clipboard

Merge use references to src instead of deep copying

Open Segflow opened this issue 2 years ago • 0 comments

type TestStruct struct {
  ID   string
  Deep map[string]interface{}
}
t0 := TestStruct{}
t1 := TestStruct{
  ID:   "5",
  Deep: map[string]interface{}{"workers": map[string]interface{}{"num": 5}},
}

mergo.Merge(&t0, t1)

fmt.Printf("Address of t0.Deep['worker'] = %p\n", t0.Deep["workers"])
fmt.Printf("Address of t1.Deep['worker'] = %p\n", t1.Deep["workers"])
t0.Deep["workers"].(map[string]interface{})["num"] = "11111" // Any mutation here is also observed in t1

fmt.Println(t0)
fmt.Println(t1)

See in go playground

Expected behavior:

I except t0 to have a copy of the map not a reference to it.

Current behavior

The above snippet outputs:

Address of t0.Deep['worker'] = 0xc0000121e0
Address of t1.Deep['worker'] = 0xc0000121e0
{5 map[workers:map[num:11111]]}  // t0
{5 map[workers:map[num:11111]]}  // t1: See how we also see 11111

Segflow avatar Jun 22 '22 18:06 Segflow