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

huangapple go评论152阅读模式
英文:

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
}

<kbd>playground</kbd>

英文:

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
}

<kbd>playground</kbd>

答案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 [&quot;name&quot;]=&quot;Kube&quot;
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)

huangapple
  • 本文由 发表于 2015年9月26日 11:41:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/32793391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定