func testAddDataToResult() { var a map[string]interface{} Println(a, &a) addDataToResult(a, "aa", "bb") Println(a, &a) } func addDataToResult(result map[string]interface{}, key string, val interface{}) { if result == nil { Println("nil result:", result, &result) result = map[string]interface{}{key: val} //result[key] = val Println("nil result:", result, &result) return } result[key] = val Println("result:", result, &result) } 结果
map[] &map[]
nil result: map[] &map[]
nil result: map[aa:bb] &map[aa:bb]
map[] &map[]
var a map[string]interface{} Println(a, &a) addDataToResult(a, "aa", "bb") Println(a, &a) } func addDataToResult(result map[string]interface{}, key string, val interface{}) { if result == nil { Println("nil result:", result, &result) //result = map[string]interface{}{key: val} result[key] = val Println("nil result:", result, &result) return } result[key] = val Println("result:", result, &result) } 结果 map[] &map[] nil result: map[] &map[] panic: assignment to entry in nil map
func testAddDataToResult() { var a = map[string]interface{}{} Println(a, &a) addDataToResult(a, "aa", "bb") Println(a, &a) } func addDataToResult(result map[string]interface{}, key string, val interface{}) { if result == nil { Println("nil result:", result, &result) //result = map[string]interface{}{key: val} result[key] = val Println("nil result:", result, &result) return } result[key] = val Println("result:", result, &result) } 结果 map[] &map[] result: map[aa:bb] &map[aa:bb] map[aa:bb] &map[aa:bb]
第一个测试将nil值的map[string]interface{}传到函数,修改后原函数里的值没改变
第二个测试将nil值的map[string]interface{}传入到函数,直接result[key]=val,panic: assignment to entry in nil map
第三个测试将不为nil值的map[string]interface{}传入到函数,直接result[key]=val,原函数的map被改变了
func testAddDataToResult() { var a interface{} Println(a, &a) addDataToResult(a, "aa", "bb") Println(a, &a) } func addDataToResult(result interface{}, key string, val interface{}) { if result == nil { Println("nil result:", result, &result) result = map[string]interface{}{key: val} Println("nil result:", result, &result) return } result.(map[string]interface{})[key] = val Println("result:", result, &result) } 结果0xc42000e280 nil result: 0xc42000e290 nil result: map[aa:bb] 0xc42000e290 0xc42000e280