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
+11k Golang : How to pipe input data to executing child process?
+29k Golang : Saving(serializing) and reading file with GOB
+19.8k Golang : Compare floating-point numbers
+5.3k How to check with curl if my website or the asset is gzipped ?
+16.3k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+10.9k Golang : Web routing/multiplex example
+5.1k PHP : Hide PHP version information from curl
+7.1k Golang : Example of custom handler for Gorilla's Path usage.
+11.1k Golang : Delay or limit HTTP requests example
+19.3k Golang : Close channel after ticker stopped example
+10.6k PHP : Convert(cast) bigInt to string
+16.6k Golang : read gzipped http response