【问题标题】:How to initialize a slice of maps correctly如何正确初始化一片地图
【发布时间】:2016-10-31 14:40:21
【问题描述】:

所以我希望能够创建一个映射切片,这样当我访问切片的任何元素时,我都会得到一个非零映射。

到目前为止,这是我的代码。但我得到panic: assignment to entry in nil map的错误

package main

import (
    "fmt"
)

func main() {
    all := make([]map[string]string, 3)
    first := all[0]
    first["hello"] = "world"
    fmt.Println(all)
}

【问题讨论】:

  • all[0] = map[string]string{"hello": "world"}。参加围棋之旅(再一次)。

标签: dictionary go slice


【解决方案1】:

我认为作者想用这样的默认实例预先初始化切片

func main() {
    all := make([]map[string]string, 3)
    for idx, _ := range all {
      all[idx] = map[string]string{}
    }
    first := all[0]
    first["hello"] = "world"
    fmt.Println(all)
}

【讨论】:

  • 这行得通。但我想看看是否还有其他更简单、更原生的 go like 方法来进行深度初始化。无论如何谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 2022-01-01
  • 2010-11-11
  • 2015-05-23
  • 1970-01-01
相关资源
最近更新 更多