首页 > 代码库 > go 指针(interface{},map)
go 指针(interface{},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[]
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)}结果<nil> 0xc42000e280nil result: <nil> 0xc42000e290nil result: map[aa:bb] 0xc42000e290<nil> 0xc42000e280
go 指针(interface{},map)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。