Golang : Map within a map example
Just an example of map within map in Golang. The example below demonstrates how to put declare a map with map and how to access the elements.
Putting this down here for my own future reference.
Here we go!
package main
import (
"fmt"
)
func main() {
hits := map[string]map[string]string{
"#$h-ma": map[string]string{
"AggregatorA0": "counterA0",
"AggregatorA1": "counterA1",
"AggregatorA2": "counterA2",
"AggregatorA3": "counterA3",
},
"#$h-mb": map[string]string{
"AggregatorB0": "counterB0",
"AggregatorB1n": "counterB1",
},
"#$h-mc": map[string]string{
"AggregatorC0": "counterC0",
},
}
// accessing the elements in map within map
fmt.Println(hits["#$h-mb"]["AggregatorBn"]) // empty
fmt.Println(hits["#$h-mb"]["AggregatorB1n"]) // counterB1
fmt.Println(hits["#$h-ma"]) // show all
fmt.Println(hits["#$h-ma"]["AggregatorA1"]) // counterA1
// show all
fmt.Println(hits)
}
Output:
counterB1
map[AggregatorA0:counterA0 AggregatorA1:counterA1 AggregatorA2:counterA2 AggregatorA3:counterA3]
counterA1
map[#$h-ma:map[AggregatorA2:counterA2 AggregatorA3:counterA3 AggregatorA0:counterA0 AggregatorA1:counterA1] #$h-mb:map[AggregatorB0:counterB0 AggregatorB1n:counterB1] #$h-mc:map[AggregatorC0:counterC0]]
See also : Golang : Extract or copy items from map based on value
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.1k Golang : Break string into a slice of characters example
+6.1k Golang : Detect face in uploaded photo like GPlus
+8.8k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+13.9k Golang : How to pass map to html template and access the map's elements
+8.9k Golang : Create and shuffle deck of cards example
+10.7k Golang : Replace a parameter's value inside a configuration file example
+7.8k Golang : Variadic function arguments sanity check example
+31.4k Golang : Convert an image file to []byte
+22.2k Generate checksum for a file in Go
+8.8k Golang : Simple histogram example
+9.1k Golang : Play .WAV file from command line
+27.1k PHP : Convert(cast) string to bigInt