Idiomatic way of renaming keys in map while ranging over the original map

Viewed 8135

I'm attempting to rename the keys of a map o using the keys and values of another map r.

This below attempt seems to fail for reasons I guess are related to the fact that I'm modifying the map while also ranging over it — I get an extra blank key.

I could simply copy the map over to a new destination map, however the map is part of a much more complex struct — so any attempts will require me to do some kind of recursive deep copy of that struct, which I would rather avoid.

o := make(map[string]string) // original map
r := make(map[string]string) // replacement map original -> destination keys

o["a"] = "x"
o["b"] = "y"

r["a"] = "1"
r["b"] = "2"

fmt.Println(o) // -> map[a:x b:y]

for k, v := range o {
    o[r[k]] = v
}

delete(o, "a")
delete(o, "b")

fmt.Println(o) // -> map[1:x 2:y :y]

I am expecting this to print map[1:x 2:y].

3 Answers
Related