go - 在golang的不同位置初始化不同的 map 值

标签 go struct

我正在创建一个结构图来保存不同的信息。我正在使用的示例结构是:

type Test struct{
  Value1 string
  Value2 string
  Value3 string
  Value4 string
}

func main() {
  testMap := make(map[string]*Test) //using a pointer to map
  func2(testMap)
  //pass map to another function for more additions.
}

func func2 (testMap map[string]*Test) {
  a, b := getVal(); //get some random values
  res := concat(a,b) //basically create a string key based on values a and b
  testMap[res].value1 = a   //****
  testMap[res].value2 = b
  //do something else
  testMap[res].value3 = "hello"

}

我基本上是在尝试创建一个映射并在获取它们时向其添加值,但是我在 **** 行上收到 invalid memory address or nil pointer dereference 错误(参见代码对于 ***)。

最佳答案

尝试:

func func2 (testMap map[string]*Test) {
  a, b := getVal(); //get some random values
  res := concat(a,b) //basically create a string key based on values a and b
  testMap[res] = &Test{
     Value1: a,
     Value2: b,
     Value3: "string",
  }

}

或者如果你想先创建对象,然后填充值,试试

func func2 (testMap map[string]*Test) {
  a, b := getVal(); //get some random values
  res := concat(a,b) //basically create a string key based on values a and b
  testMap[res] = &Test{}
  testMap[res].value1 = a   //****
  testMap[res].value2 = b
  //do something else
  testMap[res].value3 = "hello"

}

关于go - 在golang的不同位置初始化不同的 map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54932270/

相关文章:

Go:如何在 Go 中使用 func() bool 参数?

algorithm - 为什么这个二叉树搜索比插入花费的时间长得多?

c - 需要帮助将数组结构更改为结构数组

c - qsort() 性能问题

arrays - 包含结构数组的 MAT 文件的导入 [] - 仅导入第一个元素?

swift - 结构变异函数调用同一结构的另一个实例中的函数

Golang,更改自定义客户端 MaxIdleConnsPerHost 的结构

http - 使用 go net/http mux 提供单页应用程序

go - 如何提取表单数据字段名称

arrays - go 垃圾会收集部分 slice 吗?