Reputation: 6119
If I have a nested map variable like this inside a struct:
type someStruct struct {
nestedMap map[int]map[string]string
}
var ss = someStruct {
nestedMap: make(map[int]map[string]string),
}
This does not work and does a runtime error.
How do I initialize it?
Upvotes: 8
Views: 10858
Reputation: 81
While the accespted answer is true, what I've found is that in all situations I've had so far I could just create a complex key instead of nested map.
type key struct {
intKey int
strKey string
}
Then just initiate the map in one line:
m := make(map[key]string)
Upvotes: 3
Reputation: 2304
Initilize nested map like this:
temp := make(map[string]string,1)
temp ["name"]="Kube"
ss.nestedMap [2] = temp
fmt.Println(ss)
Upvotes: 1
Reputation: 99361
You have to make the child maps as well.
func (s *someStruct) Set(i int, k, v string) {
child, ok := s.nestedMap[i]
if !ok {
child = map[string]string{}
s.nestedMap[i] = child
}
child[k] = v
}
Upvotes: 8