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