简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM