79372121

Date: 2025-01-20 17:09:48
Score: 1.5
Natty:
Report link

The following statement does not "save" the lookup map into the data slice in the sense that it would make a backup/copy:

data = append(data, lookup)

In Go, "map types are reference types, like pointers or slices" (according to this blog post). So, lookup refers to an internal map struct stored somewhere in memory. When you append lookup to data, you are copying the reference into the slice, not the whole map data. Afterwards, both lookup and data[0] refer to the same map.

What you can do is either cloning the map (as @legec suggested in the comments):

data = append(data, maps.Clone(lookup))

or, assuming your are looping somewhere, just create a new lookup map for each iteration in the loop body:

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

for i := range whatever {
    lookup := make(map[string]string)
    // fill lookup map ...
    data = append(data, lookup)
}
Reasons:
  • Blacklisted phrase (1): this blog
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @legec
  • Low reputation (0.5):
Posted by: mwopitz