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
+7.9k Golang : Handle Palindrome string with case sensitivity and unicode
+21.1k Golang : How to get time zone and load different time zone?
+30.3k Golang : Generate random string
+7.2k Golang : How to convert strange string to JSON with json.MarshalIndent
+7.6k Golang : get the current working directory of a running program
+8.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+11.5k Golang : Find age or leap age from date of birth example
+13.5k Golang : Image to ASCII art example
+5.2k Javascript : Change page title to get viewer attention
+13.3k Golang : Read from buffered reader until specific number of bytes
+15.6k Golang : How to login and logout with JWT example
+27k Golang : Find files by name - cross platform example