go 指针(interface{},map)

Posted dy blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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> 0xc42000e280
nil result: <nil> 0xc42000e290
nil result: map[aa:bb] 0xc42000e290
<nil> 0xc42000e280

  

 

以上是关于go 指针(interface{},map)的主要内容,如果未能解决你的问题,请参考以下文章

go语言-interface的值接收和指针接受的区别

go语言-interface的值接收和指针接受的区别

go语言-interface的值接收和指针接受的区别

为啥在 Go 中将指针放入 interface 会导致反射丢失类型的名称?

图解Go的unsafe.Pointer

图解Go的unsafe.Pointer