arr := [...]int{0,1,2,3,4,5,6,7}
fmt.Printf("arr[2:6]= ", arr[2: 6])
fmt.Printf("\n a[:6] = ", arr[:6])
s1 := arr[2:]
fmt.Printf("\n arr[2:] = ", s1)
s2 :=arr[:]
fmt.Printf("\n arr[:] =", s2)
updateSlice(s1)
fmt.Printf("\n arr[:] = ", s1)
s1 = arr[2:6]
s2 = s1[3:6]
fmt.Printf("\n s1=%v len(s1)=%d, cap(s1)=%d", s1, len(s1), cap(s1))
fmt.Printf("\n s2=%v len(s2)=%d, cap(s2)=%d", s2, len(s2), cap(s2))
输出
arr[2:6]= %!(EXTRA []int=[2 3 4 5])
a[:6] = %!(EXTRA []int=[0 1 2 3 4 5])
arr[2:] = %!(EXTRA []int=[2 3 4 5 6 7])
arr[:] =%!(EXTRA []int=[0 1 2 3 4 5 6 7])
arr[:] = %!(EXTRA []int=[100 3 4 5 6 7])
s1=[100 3 4 5] len(s1)=4, cap(s1)=6
s2=[5 6 7] len(s2)=3, cap(s2)=3
s1的值为【2 4 5】 s2的值为[5 6]
slice可以向后扩展,不可以向前扩展
s[i]不可以超越len(s),向后扩展不可以超越底层数组cap(s)
切片的创建
s1 := []int{1,2,3,4}
fmt.Printf("s1 = ", s1)
//make函数,格式(切片类型,长度,容量)
s2 := make([]int, 5, 10)
fmt.Printf("s1 = ", s2)
//make函数,格式(切片类型,长度) 长度和容量相同
s3 := make([]int, 5)
fmt.Printf("s3 = ", s3)
array := []int{1,2,3,4,5,6,7,8,9}
//操作某个元素,和数组操作方式一样
data := array[1]
fmt.Println("data = ", data)
s3 := array[:6]//从0开始,取6个元素,容量也是6,常用
fmt.Println("s3 = ", s3)
s4 := array[3:]//从下标为3开始,到结束
fmt.Println("s4 = ", s4)