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
+24.1k Golang : GORM read from database example
+10.4k Android Studio : Checkbox for user to select options example
+6.6k Golang : Get expvar(export variables) to work with multiplexer
+4.2k Linux/MacOSX : Search and delete files by extension
+6.4k Elasticsearch : Shutdown a local node
+13.2k Golang : Count number of runes in string
+26.3k Golang : Encrypt and decrypt data with AES crypto
+4.5k Unix/Linux : How to pipe/save output of a command to file?
+8.5k Android Studio : Image button and button example
+12.6k Golang : Convert IPv4 address to packed 32-bit binary format
+5.6k Golang : Markov chains to predict probability of next state example
+18.9k Mac OSX : Homebrew and Golang