arrays - How to create an associative map in golang? -


i'm trying create 'associative' map. issue supermap collects values of amap. if want store 1 instance of amap on each endup storing current instance plus previous loops. supermap[value] = amap[value] . snippet below stores supermap[value] = amap. reason can't find way fix this. if delete old values of amap after each loop deleted supermap well.

  package main      import (     "fmt" )  func main() {      adata := map[int]string{         0: "apple",         1: "samsung",         2: "htc",         3: "sony",     }      dir := []string{"user", "doc", "bin", "src"}      amap := make(map[int]string)     supermap := make(map[string]map[int]string)      k, v := range dir {         amap[k] = adata[k]         supermap[v] = amap       }     hello(supermap)  }  func hello(supermap map[string]map[int]string) {     fmt.printf("supermap of user %v \n", supermap["user"])      cnt := len(supermap["user"])     if cnt > 1{       fmt.printf("expected 1 value received %v", cnt)     } } 

play

as arjan said in comment, need move creation of amap loop. reason because, in original code posted dealing 1 instance of amap in memory. means, 1 map called amap created , when assign variable value of amap assigning reference. means, variable hold reference (to amap) state mutated, observed in other variables holding reference because resolve same object in memory.

when amap moved for/range loop, means 4 individual instances of amap created own memory. mutating state of 1 of amaps not affect others because own objects in memory. now, if took 1 of objects , made reference again variable you'd end in same boat first case.

package main  import (     "fmt" )  func main() {      adata := map[int]string{         0: "apple",         1: "samsung",         2: "htc",         3: "sony",     }      dir := []string{"user", "doc", "bin", "src"}      //amap := make(map[int]string) //only 1 map instance created in memory     supermap := make(map[string]map[int]string)      k, v := range dir {         //multiple map instances created in memory         amap := make(map[int]string)         amap[k] = adata[k]         supermap[v] = amap      }      hello(supermap) }  func hello(supermap map[string]map[int]string) {     fmt.printf("supermap of user %v \n", supermap["user"])     cnt := len(supermap["user"])      if cnt > 1 {         fmt.printf("expected 1 value received %v", cnt)     } } 

Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -