go - How to copy a map? -


i'm trying copy contents of map ( amap ) inside 1 (asupermap) , clear amap can take new values on next iteration/loop. issue can't clear map without clear reference in supermap well. here pseudo code.

for := range fruits{         amap := make(map[string]astruct)         asupermap := make(map[string]map[string]astruct)          x := range something{             amap[x] = adata             asupermap[y] = amap             delete(amap, x)     } //save asupermap   saveasupermap(something)  } 

i've tried dynamic stuff throws error (cannot assign nil)

asupermap[y][x] = adata 

the question how can create associative map ? in php use asupermap[y][x] = adata. seems golang doesn't have obvious method. if delete delete(amap, x) reference super map deleted well. if don't delete supermap ends duplicate data. on each loop gets amap new value plus old values.

you not copying map, reference map. delete modifies values in both original map , super map. copy map, have use for loop this:

for k,v := range originalmap {   newmap[k] = v } 

here's example now-retired documentation:

// create original map originalmap := make(map[string]int) originalmap["one"] = 1 originalmap["two"] = 2  // create target map targetmap := make(map[string]int)  // copy original map target map key, value := range originalmap {   targetmap[key] = value } 

this content ported on stack overflow documentation, retired. access source , attribution please access docs archive , reference topic id: 732 , example id: 9834.


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 -