Alex
Alex

Reputation: 6119

How can I initialize a nested map inside a struct in Go?

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

Answers (3)

pstoyanov
pstoyanov

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

Animesh Kumar Paul
Animesh Kumar Paul

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

OneOfOne
OneOfOne

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
}

playground

Upvotes: 8

Related Questions