dongniechi7825 2017-11-15 12:33
浏览 57
已采纳

追加地图数组会替换最新的地图项中所有以前的数组项

The question may sound very stupid but I really don't understand what's wrong.

I want to create an array of maps like this:

values := make([]map[string]string, 0)

Then I create some map:

row := make(map[string]string)
row["item1"] = "value1"
row["item2"] = "value2"

Then append it to the array:

values = append(values, row)

Printing values now gives:

[map[item1:value1 item2:value2]]

Do the same using some other values:

row["item1"] = "value3"
row["item2"] = "value4"
values = append(values, row)

Now printing values gives:

[map[item1:value3 item2:value4] map[item1:value3 item2:value4]]

So the first array item = the second one. What can cause this?

Full code:

package main

import "fmt"

func main() {
  values := make([]map[string]string, 0)
  row := make(map[string]string)
  row["item1"] = "value1"
  row["item2"] = "value2"
  values = append(values, row)
  fmt.Println(values)
  row["item1"] = "value3"
  row["item2"] = "value4"
  values = append(values, row)
  fmt.Println(values)
}
  • 写回答

2条回答 默认 最新

  • duanqian3953 2017-11-15 12:40
    关注

    maps variables are pointers to a map so assume that your row map is in 0x50 memory address, then your values array would be some like this

    values := {{0x50}, {0x50}}
    

    so both will change by changing row. a simple way to do that is to repeat making row again after first println or change the name of second map

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?