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
+19.5k Golang : Measure http.Get() execution time
+9.8k Golang : Channels and buffered channels examples
+5.8k Golang : How to verify input is rune?
+19k Golang : Execute shell command
+10.1k Golang : Convert file unix timestamp to UTC time example
+6.4k Elasticsearch : Shutdown a local node
+14.8k Golang : How do I get the local IP (non-loopback) address ?
+16.4k Golang : Gzip file example
+4.6k Fix Google Analytics Redundant Hostnames problem
+23k Golang : Get ASCII code from a key press(cross-platform) example
+12.1k Golang : Get month name from date example
+9k Golang : Generate random Chinese, Japanese, Korean and other runes