go切片的浅拷贝问题

14 阅读1分钟
func testCopy() {
   test1 := []int{1, 2, 3, 4, 5}
   test2 := test1
   test1 = test1[0:0]
   for i, v := range test2 {
      if i == 0 {
         test1 = append(test1, 7, 8, 9, 10, 11)
      }
      fmt.Println(v)
   }
   fmt.Printf("%p\n", test1)
   fmt.Printf("%p\n", test2)
}

这段代码的输出如下:

1
8
9
10
11
0x14000016210
0x1400001621

请谨慎的使用浅拷贝,在不发生扩容的情况下也危险的很呐