Map of Map In golang

Hiii
I m calling function three times but result getting value double times,

package main

import ("github.com/test/server" 
        "fmt")

var eventInfo = map[string]map[int]int{}
var nestedEventInfo = map[int]int{}
var count int = 0
func Event(eventName string) {
	if eventInfo[eventName] != nil {
		count += 1
		eventInfo[eventName][server.GetWindow()] = count
	} else {
		eventInfo[eventName] = nestedEventInfo
		count = 1
		eventInfo[eventName][server.GetWindow()] = count
	}
	fmt.Println(eventInfo)
}
func main() {
	Event("GET")
	Event("GET")
	Event("POST")
}

outPut:

map[GET:map[1:1]]
map[GET:map[1:2]]
map[GET:map[1:1] POST:map[1:1]]

What output do you expect? To me the output seems to be in line with the code.

Whenever the entry does not exist for a given eventName, you

which initializes that entry with the nestedEventInfo map. This is a specific map instance. It is the same map every time. So eventInfo["GET"] and eventInfo["POST"] end up both referencing the same map, nestedEventInfo.

You probably meant

eventInfo[eventName] = map[int]int{}

instead. (Or make(map[int]int)).

1 Like

I expect output like this

map[GET:map[1:1]]
map[GET:map[1:2]]
map[POST:map[1:1]]

Okay Thank You

Thanks for the reply. I think the problem is that Event() adds everything into the same global map eventInfo.

  • The first call adds a new “GET” element to eventInfo.
  • The second call finds a “GET” element and increases the count.
  • The third call adds a new “POST” element to eventInfo. Now eventInfo contains two elements.

If the third call shall just output map[POST:map[1:1]], then Event() needs to either delete the “GET” element first, or create a new map each time. This depends on what you want to achieve with this code.

Edited to add: The issue that @calmh explained is a separate one and also needs to get fixed.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.