golang中对切片进行切片取值和append追加的经典案例

案例1:

func main() {
	slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	s1 := slice[2:5]  // s1=[2, 3, 4], len=3, cap=8
	s2 := s1[2:6:7]  // s2=[4, 5, 6, 7], len=4, cap=5
	s2 = append(s2, 100)  // s2=[4, 5, 6, 7, 100], len=5, cap=5, 此时也会影响slice的变化,将slice的8->100
	s2 = append(s2, 200)  // s2扩容,底层数组复制,s2=[4, 5, 6, 7, 100, 200], len=6, cap=10
	s1[2] = 20  // s1=[2, 3, 20],  slice中的4->20
	fmt.Println(s1)  // [2, 3, 20]
	fmt.Println(s2)  // [4, 5, 6, 7, 100, 200]
	fmt.Println(slice)  // [0, 1, 2, 3, 20, 5, 6, 7, 100, 9]
}

案例2:

func main() {
	slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	s1 := slice[2:5:5]  // s1=[2, 3, 4], len=3, cap=3
	s2 := s1[2:3:3]  // s2=[4], len=1, cap=1
	s2 = append(s2, 100)  // s2=[4, 100], len=2, cap=2
	s2 = append(s2, 200)  // s2=[4, 100, 200], len=3, cap=4
	s1[2] = 20  // s1=[2, 3, 20],  slice中的4->20
	fmt.Println(s1)  // [2, 3, 20]
	fmt.Println(s2)  // [4, 100, 200]
	fmt.Println(slice)  // [0, 1, 2, 3, 20, 5, 6, 7, 8, 9]
}

案例3:

func main() {
	slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	s1 := slice[2:5]  // s1=[2, 3, 4] len=3 cap=8
	s2 := s1[2:6:7]  // s2=[4, 5, 6, 7] len=4 cap=5
	// 下面代码会改变底层数组的值:8->100,因为s1和slice也引用的底层数组,所以它俩都会受到影响
	// 此时slice = [0, 1, 2, 3, 4, 5, 6, 7, 100, 9], 由于s1的长度为3,所以它虽然底层数组收到了影响,但是它没变化
	s2 = append(s2, 100)  // s2=[4, 5, 6, 7, 100] len=5 cap=5
	// s2发生了扩容,底层数组复制,增加的200元素不会对s1和slice的底层数组产生影响
	s2 = append(s2, 200)  // s2=[4, 5, 6, 7, 100, 200] len=6 cap=10
	s1[2] = 20  // s1=[2, 3, 20] len=3 cap=8, slice的4->20  slice=[0, 1, 2, 3, 20, 5, 6, 7, 100, 9]
	fmt.Println(s1)  // [2, 3, 20]
	fmt.Println(s2)  // [4, 5, 6, 7, 100, 200]
	fmt.Println(slice)  // [0, 1, 2, 3, 20, 5, 6, 7, 100, 9]
}

在提一点,打印s1的时候只会打印出三个元素,虽然它的底层数组不止3个元素

参考文档

posted @ 2022-03-14 14:09  专职  阅读(351)  评论(0编辑  收藏  举报