I am trying to remove the same key from two maps using reflection. However, removing it from the first map is causing a change to the key value. Is this WAI or a bug.
Code at (http://play.golang.org/p/MIkFP_Zrxb):
func main() {
m1 := map[string]bool{"a": true, "b": true}
m2 := map[string]bool{"a": true, "b": true}
fmt.Println(m1)
v1 := reflect.ValueOf(m1)
k := v1.MapKeys()[0]
fmt.Println("KEY BEFORE", k)
v1.SetMapIndex(k, reflect.Value{}) // COMMENT THIS OUT
fmt.Println("m1:", m1)
fmt.Println("KEY AFTER", k)
v2 := reflect.ValueOf(m2)
v2.SetMapIndex(k, reflect.Value{})
fmt.Println("KEY AFTER SECOND CALL", k)
fmt.Println("m2:", m2)
}
produces this output:
map[a:true b:true]
KEY BEFORE a
m1: map[b:true]
KEY AFTER
KEY AFTER SECOND CALL
m2: map[a:true b:true]
Notice that the "a" value is not removed from m2. Commenting out the indicated line causes the call to v2.SetMapIndex to work.
Also notice that the value of "k" changes after the call to SetMapIndex. That appears to be the reason that SetMapIndex isn't working. Can anyone offer an explanation? Is this a bug? Any suggested workaround?
Thanks.