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

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

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

问题

如果我有一个嵌套的映射变量,像这样在一个结构体内:

  1. type someStruct struct {
  2. nestedMap map[int]map[string]string
  3. }
  4. var ss = someStruct {
  5. nestedMap: make(map[int]map[string]string),
  6. }

这样做会导致运行时错误。

我该如何初始化它?

英文:

If I have a nested map variable like this inside a struct:

  1. type someStruct struct {
  2. nestedMap map[int]map[string]string
  3. }
  4. var ss = someStruct {
  5. nestedMap: make(map[int]map[string]string),
  6. }

This does not work and does a runtime error.

How do I initialize it?

答案1

得分: 7

你必须也要创建子地图。

  1. func (s *someStruct) Set(i int, k, v string) {
  2. child, ok := s.nestedMap[i]
  3. if !ok {
  4. child = map[string]string{}
  5. s.nestedMap[i] = child
  6. }
  7. child[k] = v
  8. }

<kbd>playground</kbd>

英文:

You have to make the child maps as well.

  1. func (s *someStruct) Set(i int, k, v string) {
  2. child, ok := s.nestedMap[i]
  3. if !ok {
  4. child = map[string]string{}
  5. s.nestedMap[i] = child
  6. }
  7. child[k] = v
  8. }

<kbd>playground</kbd>

答案2

得分: 1

初始化嵌套的映射可以像这样进行:

  1. temp := make(map[string]string, 1)
  2. temp["name"] = "Kube"
  3. ss.nestedMap[2] = temp
  4. fmt.Println(ss)

请注意,这只是一个示例代码,ss 是一个包含嵌套映射的结构体或变量。

英文:

Initilize nested map like this:

  1. temp := make(map[string]string,1)
  2. temp [&quot;name&quot;]=&quot;Kube&quot;
  3. ss.nestedMap [2] = temp
  4. fmt.Println(ss)

答案3

得分: 1

虽然接受的答案是正确的,但我发现在我迄今遇到的所有情况中,我只需创建一个复杂的键而不是嵌套的映射。

  1. type key struct {
  2. intKey int
  3. strKey string
  4. }
  5. 然后只需在一行中初始化映射
  6. 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.

  1. type key struct {
  2. intKey int
  3. strKey string
  4. }

Then just initiate the map in one line:

  1. 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:

确定