Here's my code
{
saruman := map[string]int{
"power": 150,
"skills": 200,
"knowledge": 380,
}
gandalf := map[string]int{
"power": 180,
"skills": 210,
"knowledge": 240,
}
wizards := make(map[string]interface{})
wizards["saruman"] = saruman
wizards["gandalf"] = gandalf
fmt.Println(wizards)
//OK map[gandalf:map[knowledge:240 power:180 skills:210] saruman:map[knowledge:380 power:150 skills:200]]
//change gandalf property
wizards["gandalf"]["knowledge"] = 310
fmt.Println(wizards)
}
In the last line, we get:
NOK invalid operation: wizards["gandalf"]["knowledge"] (type interface {} does not support indexing)
CodePudding user response:
You cannot use ["key"]
to access a structure that golang does not know about. Because it is an interface{}
the value behind gandalf could be anything.
wizards["gandalf"] = map[string]int{
"knowledge": 310,
}
You have to specify the type of data you are interacting with.
Playground: https://goplay.tools/snippet/O62ara8JbUv
CodePudding user response:
Need to cast it.
{
saruman := map[string]int{
"power": 150,
"skills": 200,
"knowledge": 380,
}
gandalf := map[string]int{
"power": 180,
"skills": 210,
"knowledge": 240,
}
wizards := make(map[string]interface{})
wizards["saruman"] = saruman
wizards["gandalf"] = gandalf
fmt.Println(wizards)
//OK map[gandalf:map[knowledge:240 power:180 skills:210] saruman:map[knowledge:380 power:150 skills:200]]
//change gandalf property
wizards["gandalf"].(map[string]int)["knowledge"] = 10
fmt.Println(wizards)
}
CodePudding user response:
This is the easier way:
one line code
wizards["gandalf"].(map[string]int)["knowledge"] = 110
Full example:
saruman := map[string]int{
"power": 150,
"skills": 200,
"knowledge": 380,
}
gandalf := map[string]int{
"power": 180,
"skills": 210,
"knowledge": 240,
}
wizards := make(map[string]interface{})
wizards["saruman"] = saruman
wizards["gandalf"] = gandalf
// fmt.Println(wizards)
// OK map[gandalf:map[knowledge:240 power:180 skills:210] saruman:map[knowledge:380 power:150 skills:200]]
// change gandalf property
wizards["gandalf"].(map[string]int)["knowledge"] = 110
fmt.Println(wizards["gandalf"].(map[string]int)["knowledge"])