切片的运用
package main
import "fmt"
func main() {
/*
数组array:
存储一组相同数据类型的数据结构
特点:定长
切片Slice:
同数组类似,也叫做边长数组或动态数组。
特点:变长
是一个引用类型的容器,指向了一个底层数组
make()
func make(t Type,size ...IntegerType)Type
第一个参数:类型
slice,map,chan
第二个参数:长度
实际存储元素的数量
第三个参数:容量cap
最多能够存储的元素的数量
append():专门用于向切片的尾部追加元素
sliece = append(slice,elem1,elem2)
sliece = append(slice,anotherSlilce...)
*/
//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
s3 :=make([]int,3,8)
fmt.Println(s3)
fmt.Printf("容量:%d,长度:%d\n",cap(s3),len(s3))
s3[0] = 1
s3[1] = 2
s3[2] = 3
fmt.Println(s3)
//fmt.Println(s3[3])//panic: runtime error: index out of range [3] with length 3
//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)
s4 = append(s4,s3...)
fmt.Println(s4)
//遍历切片
for i :=0;i <len(s4);i++{
fmt.Println(s4[i])
}
for i,v :=range s4{
fmt.Printf("%d-->%d\n",i,v)
}
}
运行输出:
[1 2 3 4]
[]
[1 2 3 4]
[4]int,[]int
[0 0 0]
容量:8,长度:3
[1 2 3]
[]
[1 2]
[1 2 3 4 5 6 7]
[1 2 3 4 5 6 7 1 2 3]
1
2
3
4
5
6
7
1
2
3
0-->1
1-->2
2-->3
3-->4
4-->5
5-->6
6-->7
7-->1
8-->2
9-->3
Process finished with exit code 0
切片的扩容和内存分析
package main
import "fmt"
func main() {
/*
切片slice:
1.每一个切片引用一个底层数组
2.切片本身不存储任何数据,都是这个底层数组存储,所以修改切片也就是修改这个数组中的数组
3.当向切片中添加数据时,如果没有超过容量,直接添加,如果超过容量,自动扩容(成倍增长)
4.切片一旦扩容,就是重新指向一个新的底层数组
扩容:
s1:3-->6-->12-->24
s2:4-->8-->16-->32...
*/
s1 := []int{1,2,3}
fmt.Println(s1)
fmt.Printf("len:%d,cap:%d\n",len(s1),cap(s1)) //len:3,cap:3
fmt.Printf("%p\n",s1)
s1 = append(s1,4,5)
fmt.Println(s1)
fmt.Printf("len:%d,cap:%d\n",len(s1),cap(s1)) //len:5,cap:6
fmt.Printf("%p\n",s1)
s1 = append(s1,6,7,8)
fmt.Println(s1)
fmt.Printf("len:%d,cap:%d\n",len(s1),cap(s1)) //len:8,cap:12
fmt.Printf("%p\n",s1)
s1 = append(s1,9,10)
fmt.Println(s1)
fmt.Printf("len:%d,cap:%d\n",len(s1),cap(s1)) //len:10,cap:12
fmt.Printf("%p\n",s1)
s1 = append(s1,11,12,13,14,15)
fmt.Println(s1)
fmt.Printf("len:%d,cap:%d\n",len(s1),cap(s1)) //len:15,cap:24
fmt.Printf("%p\n",s1)
}
运行输出:
[1 2 3]
len:3,cap:3
0xc0000143c0
[1 2 3 4 5]
len:5,cap:6
0xc00000c360
[1 2 3 4 5 6 7 8]
len:8,cap:12
0xc000042060
[1 2 3 4 5 6 7 8 9 10]
len:10,cap:12
0xc000042060
[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
len:15,cap:24
0xc000102000
Process finished with exit code 0
读完点个赞,给我的坚持更新注入新的活力。
2022.05.16日更 70/365 天
公众号:3天时间
往期同类文章:
GO学习 多维数组
GO学习 Array类型和排序
GO学习 Array
GO学习 goto语句和随机函数