// code_013_slice_usage project main.go
package main
import (
"fmt"
)
func test(s []int) {
s[0] = -1
fmt.Println("test:")
for i, v := range s {
fmt.Printf("s[%d]=%d\n", i, v)
}
fmt.Println("\n")
}
func main() {
// var s1 []int
// s2 := []int
// var s3 []int = make([]int ,0)
// s4 :=make([]int, 0, 0)
s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s1 := s[2:5]
fmt.Println(s1)
s2 := s1[2:6]
s2[3] = 200
fmt.Println(s2)
fmt.Println(s)
//内建函数的使用
//1)append函数向slice尾部添加数据,返回新的slice对象
var ss []int
ss = append(ss, 1)
ss = append(ss, 2, 3)
ss = append(ss, 4, 5, 6)
fmt.Println(ss)
ss2 := make([]int, 5)
ss2 = append(ss2, 6)
fmt.Println(ss2)
ss3 := []int{1, 2, 3}
ss3 = append(ss3, 4, 5)
fmt.Println(ss3)
//append函数会智能地底层数组的容量增长,一旦超过原底层数组容量
//通常以2倍容量重新分配底层数组,并复制原来的数据
sss := make([]int, 0, 1)
c := cap(sss)
for i := 0; i < 50; i++ {
sss = append(sss, i)
if n := cap(sss); n > c {
fmt.Printf("cap:%d -> %d\n", c, n)
c = n
}
}
//copy
//函数copy在两个slice间赋值数据
//赋值长度以len小为准,两个silce可指向同一底层数组
data := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
v1 := data[8:] //{8, 9}
v2 := data[:5] //{0, 1, 2, 3, 4}
copy(v2, v1) // dst:s2, src:s1
fmt.Println(v2) //[8 9 2 3 4]
fmt.Println(data) //[8 9 2 3 4 5 6 7 8 9]
//切片做函数参数
slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
test(slice)
fmt.Println("main:")
for i, v := range slice {
fmt.Printf("slice[%d]=%d\n", i, v)
}
//备注:底层数组的值被改变了。
fmt.Println("\n")
}