代码

func slicetest() {
	//浅拷贝
	a := []int{1, 2, 3, 4, 5, 6}
	fmt.Printf("a地址1%p\n", a)
	b := a[0:3]
	fmt.Println("a is:", a)
	fmt.Println("b is:", b)
	fmt.Printf("a地址2:%p\n", a)
	fmt.Printf("b地址:%p\n", b)
	b[0] = 100
	fmt.Println("a is:", a)
	fmt.Println("b is:", b)
	c := make([]int, 3, 3)
	c = a[0:3]
	fmt.Println("c is:", c)
	fmt.Printf("c地址:%p\n", c)

	//深拷贝

	// 当元素数量超过容量
	// 切片会在底层申请新的数组
	s1 := []int{1, 2, 3, 4, 5, 6}
	s2 := s1
	fmt.Printf("s1地址%p,s2地址%p\n", s1, s2)
	s1 = append(s1, 100)
	s2[0] = 200
	fmt.Printf("s1地址%p,s2地址%p\n", s1, s2)
	fmt.Println("s1 is:", s1)
	fmt.Println("s2 is:", s2)
	// copy 函数提供深拷贝功能
	// 但需要在拷贝前申请空间
	s3 := make([]int, 4, 4)
	s4 := make([]int, 5, 5)
	fmt.Println(copy(s3, s1)) //4
	fmt.Println(copy(s4, s1)) //5
	s3[0] = 300
	s4[0] = 400
	fmt.Println("s1 is:", s1)
	fmt.Println("s3 is:", s3)
	fmt.Println("s4 is:", s4)
}

结果

a地址10xc0000720c0
a is: [1 2 3 4 5 6]
b is: [1 2 3]
a地址2:0xc0000720c0
b地址:0xc0000720c0
a is: [100 2 3 4 5 6]
b is: [100 2 3]
c is: [100 2 3]
c地址:0xc0000720c0
s1地址0xc0000720f0,s2地址0xc0000720f0
s1地址0xc000050060,s2地址0xc0000720f0
s1 is: [1 2 3 4 5 6 100]
s2 is: [200 2 3 4 5 6]
4
5
s1 is: [1 2 3 4 5 6 100]
s3 is: [300 2 3 4]
s4 is: [400 2 3 4 5]

分析

a和b同时指向同一个地址0xc0000720c0
通过a和b都可以改变值,a值变了b的值也变了
apend和copy函数可以实现深拷贝