我正在创建一个结构图来保存不同的信息。我正在使用的示例结构是:
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
错误(请参阅***的代码)。
答案 0 :(得分:1)
尝试:
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"
}