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

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)
}

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

Got in a minute after posting the question...

Looks like append doesn't copy map, just inserts the same.. So recreating the map each time I need to append it helps:

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)
  row2 := make(map[string]string)
  row2["item1"] = "value3"
  row2["item2"] = "value4"
  values = append(values, row2)
  fmt.Println(values)
}