切片Slice
2020-03-09 本文已影响0人
isuntong
切片


package main
import "fmt"
//21
func main() {
/*
切片slice
make()
func make(t Type, size ...IntegerType) Type
第一个参数:类型
slice、map、chan
第二个参数
长度len,实际存储语速的数量
第三个参数
容量cap,最多能够存储的元素数量
*/
// 1.数组
arr := [4]int{1,2,3,4} //定长
fmt.Println(arr)
// 2.切片
var s1 []int
fmt.Println(s1)
s2 := []int{1,2,3,4}
fmt.Println(s2)
fmt.Printf("%T,%T\n", arr, s2) //[4]int,[]int
//make
s3 := make([]int, 3, 8)
fmt.Println(s3) //[0 0 0]
fmt.Printf("容量:%d,长度:%d\n", cap(s3), len(s3)) //容量:8,长度:3
s3[0] = 1
s3[1] = 2
s3[2] = 3
fmt.Println(s3) //[1 2 3]
// fmt.Println(s3[3]) //panic(恐慌): runtime error: index out of range [3] with length 3v
//使用append才可以
s4 := make([]int, 0, 5)
fmt.Println(s4)
s4 = append(s4, 1, 2)
fmt.Println(s4)
s4 = append(s4, 3, 4, 5, 6, 7) //自动扩容
fmt.Println(s4)
//s3 追加到 s4
s4 = append(s4, s3...)
fmt.Println(s4) //[1 2 3 4 5 6 7 1 2 3]
//遍历切片
for i:=0;i<len(s4);i++ {
fmt.Println(s4[i])
}
for i,v := range s4 {
fmt.Printf("%d---->%d\n", i, v)
}
}

slice的内存分析和扩容

超出容量之后扩容会改变切片底层引用的数组的地址,每次扩容成倍扩容
在已有数组上直接创建slice

/*
在已有数组上直接创建slice
*/
a := [10]int{1,2,3,4,5,6,7,8,9,10}
fmt.Println("------------------------------")
st1 := a[:5] //1-5
st2 := a[3:8] //4-8
st3 := a[5:] //6-10
st4 := a[:] //1-10
fmt.Println("a:",a)
fmt.Println("st1:",st1)
fmt.Println("st2:",st2)
fmt.Println("st3:",st3)
fmt.Println("st4:",st4)
// 地址相同,是同一个数组
fmt.Printf("%p\n",&a)
fmt.Printf("%p\n",st1)
// 长度和容量怎么算 容量从起始位置到结束
fmt.Printf("st1 len:%d,cap:%d\n", len(st1), cap(st1)) //st1 len:5,cap:10
fmt.Printf("st2 len:%d,cap:%d\n", len(st2), cap(st2)) //st2 len:5,cap:7
fmt.Printf("st3 len:%d,cap:%d\n", len(st3), cap(st3)) //st3 len:5,cap:5
fmt.Printf("st4 len:%d,cap:%d\n", len(st4), cap(st4)) //st4 len:10,cap:10
// 更改底层数组切片的内容也会发生改变

切片是引用类型
/*
基本类型:int、float、string、bool
复合类型:array、slice、map、struct、pointer、function、chan
切片是引用类型
值类型:int float string bool array
引用类型:Slice
切片是引用类型的数据,存储了底层数组的引用
*/
ss1 := []int{1,2,3,4}
ss2 := ss1
fmt.Println(ss1,ss2) //[1 2 3 4] [1 2 3 4]
ss1[0] = 100
fmt.Println(ss1,ss2) //[100 2 3 4] [100 2 3 4]

深拷贝和浅拷贝
/*
深拷贝和浅拷贝
*/
s10 := []int{1,2,3,4}
s12 := make([]int,0) //len:0 cap:0
for i:=0;i<len(s10);i++{
s12 = append(s12,s10[i])
}
fmt.Println(s10) //[1 2 3 4]
fmt.Println(s12) //[1 2 3 4]
s10[0] = 100
fmt.Println(s10) //[100 2 3 4]
fmt.Println(s12) //[1 2 3 4]
//copy函数
s13 := []int{7,8,9}
copy(s12,s13) //将s13中的元素拷贝到s12 如果s13长度更大的话就能装几个装几个
fmt.Println(s12)
fmt.Println(s13)
copy(s13[1:], s12[2:]) //改变copy的部分
