我正在创建一个结构图来保存不同的信息。我正在使用的示例结构是:
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
错误(参见代码对于 ***)。
最佳答案
尝试:
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"
}
关于go - 在golang的不同位置初始化不同的 map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54932270/