1

I'm new to golang and kinda new to coding in general and I've been stuck on this problem. I've found multiple examples on how to do this with two layers of map but none of them scale well to three layers. I have some code that looks something like this with a nested map as part of a struct.

type someStruct struct { 

     // some other stuff 

     myMap map[int]map[int]map[int]string 

} 

func (s someStruct) aFunction() {

    //need logic to initialize the map 

    s.myMap[1][2][3] = "string" 

} 
    

Obviously, without the map being initialized this throws a panic! assignment to nil entry in map. I need a way to initialize the nested map in the func that it's used in. Or in another easily callable func.

Emma
  • 11
  • 1
  • 1
    Hi @Emma, do you want to initialize a 3-layered map, or an arbitrary N-layered map using some generic code? Also, giving some context on the task you are trying to solve might help others to answer your question, because otherwise it looks like an [XY problem](https://xyproblem.info/). – 9214 Mar 25 '21 at 21:41

1 Answers1

1

You can use a literal to initialize the map:

   s.myMap=map[int]map[int]map[int]string{1:map[int]map[int]string{2:map[int]string{3:"string"}}}

This is the extension of the syntax:

mapValue=map[type1]type2{type1Value:type2Value}
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59