go

slice

Posted by 云起 on 2022-09-16
Estimated Reading Time 3 Minutes
Words 734 In Total
Viewed Times

随写

  1. 切片:引用类型,是对数组的一个引用

  2. 底层是结构体slice

  3. 值拷贝传递

  4. string底层是byte数组,也可以进行切片操作

  5. 切片的地址是他自身结构体的地址,不是底层数组的地址

  6. slice默认浅拷贝

  7. nil切片地址指向nil,空切片地址存在数据为空

创建方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//1.声明切片
var s1 []int
if s1 == nil {
fmt.Println("是空")
} else {
fmt.Println("不是空")
}
// 2.:=
s2 := []int{}
// 3.make()
var s3 []int = make([]int, 0)
fmt.Println(s1, s2, s3)
//var slice []type = make([]type, len)
//slice := make([]type, len)
//slice := make([]type, len, cap)
// 4.初始化赋值
var s4 []int = make([]int, 0, 0)
fmt.Println(s4)
s5 := []int{1, 2, 3}
fmt.Println(s5)
// 5.从数组切片
arr := [5]int{1, 2, 3, 4, 5}
var s6 []int
// 前包后不包
s6 = arr[1:4]//
fmt.Println(s6)

切片操作

  1. 初始化操作
1
2
3
4
5
6
7
8
9
1. s[low:high,max] 从切片s索引位置low`到high处所获得的切片,len=high-low,cap=max-low`
2. s[:] 从索引位置0-len(s)-1的位置

var arr = [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
var slice0 []int = arr[2:8]
var slice1 []int = arr[0:6] //可以简写为 var slice []int = arr[:end]
var slice2 []int = arr[5:10] //可以简写为 var slice[]int = arr[start:]
var slice3 []int = arr[0:len(arr)] //var slice []int = arr[:]
var slice4 = arr[:len(arr)-1] //去掉切片的最后一个元素
  1. 切片追加(append)
1
2
3
4
5
6
7
8
9
10
var a = []int{1, 2, 3}
fmt.Printf("slice a : %v\n", a)
var b = []int{4, 5, 6}
fmt.Printf("slice b : %v\n", b)
c := append(a, b...)
fmt.Printf("slice c : %v\n", c)
d := append(c, 7)
fmt.Printf("slice d : %v\n", d)
e := append(d, 8, 9, 10)
fmt.Printf("slice e : %v\n", e)

追加策略:追加后个数少于原切片容量,直接在原数组追加;

​ 超过则通常以两倍的容量重新分配底层数组

  1. 切片拷贝(copy)
1
2
3
4
5
6
7
8
9
10
11
12
13
s1 := []int{1, 2, 3, 4, 5}
fmt.Printf("slice s1 : %v\n", s1)
s2 := make([]int, 10)
fmt.Printf("slice s2 : %v\n", s2)
copy(s2, s1)
fmt.Printf("copied slice s1 : %v\n", s1)
fmt.Printf("copied slice s2 : %v\n", s2)
s3 := []int{1, 2, 3}
fmt.Printf("slice s3 : %v\n", s3)
s3 = append(s3, s2...)
fmt.Printf("appended slice s3 : %v\n", s3)
s3 = append(s3, 4, 5, 6)
fmt.Printf("last slice s3 : %v\n", s3)

copy 在两个 slice 间复制数据,复制长度以 len 小的为准。两个 slice 可指向同一底层数组,允许元素区间重叠。

  1. 切片遍历
1
2
3
4
5
data := [...]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
slice := data[:]
for index, value := range slice {
fmt.Printf("inde : %v , value : %v\n", index, value)
}

range遍历切片,value是切片里的值拷贝

  1. 扩容策略

扩容前容量的两倍小于需扩容的容量,则直接扩容至需扩容的容量

否则,如果切片的容量小于 1024 个元素,翻倍扩容。

​ 一旦元素个数超过 1024 个元素,1.25倍扩容


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !