This is mega specific, but I need to save a dictionary to a slice. The idea is that I can fill a dict (which I call "lookup") with values, then save those values inside of a slice (which I call simply "data"), so that I can fill that same dict with other values and save them again. That way I can access those dictionaries by calling data[0] or data[1]
The issue is simply that I don't have a clue how to do that. I tried data = append(data, lookup)
after initializing data as data := make([]map[string]string, 0
, but the problem is that the values already inside of data changed alongside lookup (meaning that it got filled with, like, 100 copies of the same dict). I also tried making a type type data map[string]interface{}
- since another similar question that was asked here had that solution - and then data := []data{}
into data = append(data, lookup)
but I got a missmatched type error.
I should probably mention that lookup was initialized as lookup := make(map\[string\]string)
. Here's a more abridged version:
lookup := make(map[string]string)
//this is where I'd initialize data, had I known what type I wanted. For now, I have this:
data := make([]map[string]string, 0)
//there are also a few more variables initialized here but, I don't think they're really needed for the problem at hand
//the function keeps running, filling up lookup with keys and values. Then, I've reached a point where those values need to be saved, I try:
data = append(data, lookup)
//and then reset the values of all other variables, and get lookup ready to start again
//when I print data, however, all the dicts inside it are the same, which is equal to the last value lookup had before reaching the end. I don't get why that happens - it's not like I'm saving a pointer to lookup - and if someone knows I would give you my life.
Thanks in advance, I've been looking everywhere for an answer but I got nothing.
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)
}