2

I am iterating an array of structs which have a map field:

type Config struct {
  // ... some other fields
  KV map[string]interface{} `json:"kv"`
}

In a test file, I know KV is empty, so I am iterating the array of Config objects and assigning it a new map:

  for _, v := range wrapper.Configs { // I know this is length > 0
    newMap := map[string]interface{}{
      "key1": "val1",
      "key2": "val2",
      "key3": "val3",
    }   
    v.KV = newMap // I have first tried directly assigning. Didn't work, tried copy - didn't work either
  }
  for _, v := range wrapper.Configs {
    fmt.Println(v.KV)
  }

But after the loop, KV is always empty.

I also tried:

for _, v := range wrapper.Configs { // I know this is length > 0
    v.KV = make(map[string]interface{})
    newMap := map[string]interface{}{
      "key1": "val1",
      "key2": "val2",
      "key3": "val3",
    }   
    for kk, vv := range newMap {
      v.KV[kk] = vv
    } 

I haven't been able to identify how to do this correctly, and also, efficiently.

Searched quite a bit but my search terms gave me unrelated results.

transient_loop
  • 5,984
  • 15
  • 58
  • 117

1 Answers1

3

Assuming wrapper.Configs is a slice of structs (rather than a slice of pointers to structs), v is a copy of the item in your slice, so updates don't change the originals.

To get this code to work, you can write:

for i := range wrapper.Configs {
    v := &wrapper.Configs[i]
    ...
}
Paul Hankin
  • 54,811
  • 11
  • 92
  • 118