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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里