Gilmar Palega
Gilmar Palega

Reputation: 93

Produce a dictionary map from a map in golang

This is the code that I am trying to make run on playground: http://play.golang.org/p/zX1G50txzf

I have this map:

map[producer:Tesla model:Model S year:2015]

and I want turn this into this :

[map[field:producer value:Tesla] map[field:model value:S] map[field:year value:2015]]

but in the end I will get this:

[map[field:year value:2015] map[field:year value:2015] map[field:year value:2015]]

Looks like every time the loop iterate over the original map, I am copying the reference instead of the value, so I end up with the last value replicated 3 times, instead of one of each.

What am I missing here?

Thanks in advance.

Upvotes: 1

Views: 75

Answers (1)

user142162
user142162

Reputation:

A new temp map needs to be created on each iteration of the loop. Otherwise, you are just overwriting the same map:

for key, value := range res {
    temp := make(map[string]interface{})
    // ...
}

https://play.golang.org/p/v-RaL2fswp

Upvotes: 3

Related Questions