陷阱 - meetbill/chi GitHub Wiki

1 Go中的 for range 结合 & 取地址

https://blog.csdn.net/libinemail/article/details/120324281

2 Go map 赋值

2.1 场景

申请容器时 require.volume.attributes 会赋值给 instance.volume.attributes,多个 instance 会修改 volume.attributes,则会导致数据错乱

2.2 分析

日志:go 打印地址使用 %p,如:fmt.Printf("Address of arr: %#p\n", &arr)

2.3 map 地址

package main  
  
import (  
	"fmt"  
)  
  
func main() {  
	// 创建一个map  
	myMap := make(map[string]int)  
	myMap["one"] = 1  
  
	// 另一个变量引用同一个map  
	anotherMap := myMap  
  
	// 输出map变量的地址  
	fmt.Printf("Address of myMap variable: %p\n", &myMap)  
	fmt.Printf("Address of anotherMap variable: %p\n", &anotherMap)  
  
	// 输出map本身的地址(通过引用变量的值)  
	// 注意:这里实际上不是直接输出map的地址,而是map内容的某种表示  
	fmt.Printf("Map content (or address representation) of myMap: %v\n", myMap)  
	fmt.Printf("Map content (or address representation) of anotherMap: %v\n", anotherMap)  
  
	// 如果你真的需要map在堆上的地址,你可以通过反射获取,但这通常是不必要的  
	// 而且反射在性能上开销较大,且代码可读性较差  
}

咱们要关注的是 map 本身的地址

2.4 map 深拷贝

func deepCopyMap(m map[string]interface{}) map[string]interface{} {
    newMap := make(map[string]interface{})
    for k, v := range m {
        switch val := v.(type) {
        case map[string]interface{}:
            newMap[k] = deepCopyMap(val)
        default:
            newMap[k] = val
        }
    }
    return newMap
}