go切片、 slice 使用
slice 是对底层array的一个view
slice 被修改,array也会被修改
ptr 指向开头的元素
cap 指的是 capacity
package slices
import "fmt"
func printSlices(s []int) {
s[0] = 100
fmt.Println(s)
}
func main() {
arr := [...]int{0, 1, 2, 3, 4, 5, 6, 7}
fmt.Println(arr[2:6]) // 2;6 开始包括2,结束不包括6 [2 3 4 5]
fmt.Println(arr[:6]) // [0 1 2 3 4 5]
fmt.Println(arr[2:]) // [2 3 4 5 6 7]
fmt.Println(arr[:]) // [0 1 2 3 4 5 6 7]
fmt.Println("print slice")
s := arr[:]
printSlices(s)
fmt.Println(arr)
fmt.Println("reslice")
fmt.Println(s)
s = s[:5]
fmt.Println(s)
s = s[2:]
fmt.Println(s)
/**
slice 可以向后扩展,不可以向前扩展
s[i]不可以超过len(s),向后扩展不可以超越底层数组cap(s)
*/
fmt.Println("Extending slice")
arr = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
s1 := arr[2:6]
fmt.Printf("s1=%v, len(s1)=%d, cap(s1)=%d\n", s1, len(s1), cap(s1)) // s1=[2 3 4 5], len(s1)=4, cap(s1)=6
s2 := s1[3:5]
fmt.Printf("s2=%v, len(s2)=%d, cap(s2)=%d\n", s2, len(s2), cap(s2)) // s2=[5 6], len(s2)=2, cap(s2)=3
fmt.Println("append")
s3 := append(s2, 10) // 10替换7
s4 := append(s3, 11) // 10后面没有了,超越了cap,系统重新分配了一个更大的底层数组
s5 := append(s4, 12)
fmt.Println("s3, s4, s5 = ", s3, s4, s5) // s3, s4, s5 = [5 6 10] [5 6 10 11] [5 6 10 11 12]
fmt.Println("arr = ", arr) // arr = [0 1 2 3 4 5 6 10]
}