英文:
How can I initialize a nested map inside a struct in Go?
问题
如果我有一个嵌套的映射变量,像这样在一个结构体内:
type someStruct struct {
nestedMap map[int]map[string]string
}
var ss = someStruct {
nestedMap: make(map[int]map[string]string),
}
这样做会导致运行时错误。
我该如何初始化它?
英文:
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?
答案1
得分: 7
你必须也要创建子地图。
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
}
英文:
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
}
答案2
得分: 1
初始化嵌套的映射可以像这样进行:
temp := make(map[string]string, 1)
temp["name"] = "Kube"
ss.nestedMap[2] = temp
fmt.Println(ss)
请注意,这只是一个示例代码,ss
是一个包含嵌套映射的结构体或变量。
英文:
Initilize nested map like this:
temp := make(map[string]string,1)
temp ["name"]="Kube"
ss.nestedMap [2] = temp
fmt.Println(ss)
答案3
得分: 1
虽然接受的答案是正确的,但我发现在我迄今遇到的所有情况中,我只需创建一个复杂的键而不是嵌套的映射。
type key struct {
intKey int
strKey string
}
然后只需在一行中初始化映射:
m := make(map[key]string)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论