切片的声明package main
import "fmt"
func main() {
//声明要个长度,和容量都是1的切片s1
s1 := make([]int, 1)
//切片元素赋值
s1[0] = 10
fmt.Println("s1[0]= ", s1[0])
fmt.Println("s1 length= ", len(s1), "s1 cap= ", cap(s1))
//按需增加切片的容量。Golang 内置的 append() 函数会处理增加长度时的所有操作细节
s1 = append(s1, 10)
fmt.Println("s1 length= ", len(s1), "s1 cap= ", cap(s1))
//声明要个长度3、容量是5的切片
s2 := make([]int, 3, 5)
fmt.Println("s2 length= ", len(s2), "s2 cap= ", cap(s2))
//声明一个长度和容量都是4的切片
s3 := []int{10, 20, 30, 40}
fmt.Println("s3 length= ", len(s3), "s3 cap= ", cap(s3))
//切片声明切片
s5 := make([]int, 10)
s5[0] = 0
s5[1] = 1
s5[2] = 2
s5[3] = 3
s5[4] = 4
fmt.Println("s5 length= ", len(s5), "s5 cap= ", cap(s5))
//这里注意下cap()的计算,是从切片开始指针所指向的数组下标到数组结尾的长度
s6 := s5[:3]
fmt.Println("s6 length= ", len(s6), "s6 cap= ", cap(s6)) //cap(s6)=10 s6切片指针指向了数组最小下标0
s7 := s5[2:4]
fmt.Println("s7 length= ", len(s7), "s7 cap= ", cap(s7)) //cap(s7)=8 s7切片指针指向了数组下标2 实际底层数组长度是10
//定义一个nil 切片
var s8 []int
fmt.Println("s8 is nil= ", (s8 == nil), "s8 length= ", len(s8), "cap= ", cap(s8))
//切片Copy
s9 := []int{10, 20, 30}
s10 := make([]int, 5)
count := copy(s10, s9) //copy(目标,源)
fmt.Println(count)
fmt.Println(s10)
}