I am trying to use composite literal with maps but unable to use it as it shows some error.
please find the code below.
I am a newbie to Golang and perhaps have some less understanding about composite literals.
type Assessment struct{
StructuringForce map[string][]StructuringForce
}
type StructuringForce struct {
Principles map[string][]Capabilities
}
type Capability struct {
}
c1 := Capability{}
a1 := Assessment{
StructuringForce : map[string][]StructuringForce{
"Information Systems" , []StructuringForce{
StructuringForce{
Principles : map[string][]Capabilities{
"Integration of IT Services" ,[]Capabilities{
c1,
},
},
},
},
},
}
while constructing "a1" with composite literals I get "Missing key in map literals error".
But i can see that i have added keys.
As Volker pointed out, make
cannot be used with literals. In your case it can either be:
make(map[string][]StructuringForce)
or
map[string][]StructuringForce{}{}
Secondly, for golang map
, it's using :
to separate the key-value, so it should be like:
a := map[string]string{
"foo": "bar",
}
Thirdly, you don't have Capabilities
defined, so I suppose you're trying to do Capability
.
To sum up, the entire thing in the main
func should look like:
c1 := Capability{}
a1 := Assessment{
StructuringForce: map[string][]StructuringForce{
"Information Systems": []StructuringForce{
StructuringForce{
Principles: map[string][]Capability{
"Integration of IT Services": []Capabilities{
c1, // missing comma here as well
},
},
},
},
},
}
However, based on what you pasted, I would suggest you start from something straightforward to get started with the syntax and how to compose a map
, like Go By Examples.
Another suggestion is that you can wrap the running code in main
func when posting a SO question, which will make reproducing the issue a lot easier and more understandable to others who try to help.