duanlang1196 2019-02-28 10: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 11: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"
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部