码迷,mamicode.com
首页 > 其他好文 > 详细

go 指针(interface{},map)

时间:2017-07-09 14:43:32      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:color   sig   highlight   ddd   str   assign   size   san   []   

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> 0xc42000e280
nil result: <nil> 0xc42000e290
nil result: map[aa:bb] 0xc42000e290
<nil> 0xc42000e280

  

 

go 指针(interface{},map)

标签:color   sig   highlight   ddd   str   assign   size   san   []   

原文地址:http://www.cnblogs.com/cdyboke/p/7141373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!