8

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?

3 Answers 3

8

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
}

playground

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

1

Initilize nested map like this:

temp := make(map[string]string,1)
temp ["name"]="Kube"
ss.nestedMap [2] = temp
fmt.Println(ss)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.