0

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 ***).

4
  • That means that testMap[res] is nil. As the error says, you can't dereference (eg access fields of) a nil pointer. Commented Feb 28, 2019 at 18:45
  • that makes sense.. so how do I create an entry for map.. without knowing all the fields? (apart from getting all the fields and creating it in the end with all the values) Commented Feb 28, 2019 at 18:46
  • 2
    testMap[res] = &Test{} would insert a new empty instance, is that what you mean? Have you taken the Tour of Go? Commented Feb 28, 2019 at 18:53
  • That was it. Thank you. For some reason I missed that in the tour. I did recall it doing it by value and not through pointers, which is what confused me. Thanks! Commented Feb 28, 2019 at 19:03

1 Answer 1

1

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"

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.