duanlang1196 2019-02-28 18:44
浏览 51
已采纳

在golang中不同位置初始化地图的不同值

I'm creating a map of structs to hold different information. A sample struct I am using is:

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"

}

I'm basically trying to create a map and add values to it as I get them, but im getting a invalid memory address or nil pointer dereference error on **** line (see code for ***).

  • 写回答

1条回答 默认 最新

  • doulang9953 2019-02-28 19:01
    关注

    Try:

    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",
      }
    
    }
    

    Or if you want to create the object first, then populate the value, try

    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"
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算