Go学习学习笔记(六)切片的使用

func sliceToZeroValue() {
	//s1 := []int{1,2,3,4}
	//创建一个已知长度,没有值的切片数组
	s := make([]int, 16)
	s2 := make([]int,10,32) //可以预留cap空间
	sliceToIncrement(s)
	sliceToIncrement(s2)
}

func sliceToIncrement(s []int) {
	
	fmt.Printf("s = %v, len(s) = %d, cap(s) = %d\n", s, len(s),cap(s))


}

虽然第一个len比较长,但是第二个的预留空间cap更大
s = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0], len(s) = 16, cap(s) = 16
s = [0 0 0 0 0 0 0 0 0 0], len(s) = 10, cap(s) = 32

copy 将s1的数据copy到s2中 

func test() {
	s1 := []int{1,2,3,4}

	s2 := make([]int,10,80)
	copy(s2, s1)
	sliceToIncrement(s1)
	sliceToIncrement(s2)
}

s = [1 2 3 4], len(s) = 4, cap(s) = 4
s = [1 2 3 4 0 0 0 0 0 0], len(s) = 10, cap(s) = 80

删除切片中间的数据

func test() {
	s1 := []int{1,2,3,4}

	s2 := make([]int,10,80)
	copy(s2, s1)
	删除中间的元素  go语言处理特殊 ...
	s2 = append(s2[:2],s2[3:]...)  //到要截取元素之前结束 , 到哪里结束 之后
	s2 = append(s2[:3],s2[4:]... )
	sliceToIncrement(s1)
	sliceToIncrement(s2)
}


s = [1 2 3 4], len(s) = 4, cap(s) = 4
s = [1 2 3 0 0 0 0 0 0], len(s) = 9, cap(s) = 80

切片取出开始/最后数据

func poping() {
	s1 := []int{0,1,2,3,4,5,10}

	font := s1[0]

	s1 = s1[1:]

	sliceToIncrement(s1)
	fmt.Println("font",font)
	fmt.Println("poping is font")

	fmt.Println("poping is last")
	last := s1[len(s1) - 1] //取出最后一位
	s1 = s1[:len(s1) - 1]
	sliceToIncrement(s1)
	fmt.Println("last",last)
}


s = [1 2 3 4 5 10], len(s) = 6, cap(s) = 6
font 0
poping is font
poping is last
s = [1 2 3 4 5], len(s) = 5, cap(s) = 6
last 10

猜你喜欢

转载自blog.csdn.net/ltstud/article/details/84138091