Go

定义

切片本身不是数组,它指向底层的数组或者数组的一部分。因此,可以使用Slice来处理变长数组的应用场景。 Silice 是一种引用类型。

1、定义一个空的Slice

package main

import (
    "fmt"
)

func main() {
    var slice1 []int //定义一个Slice, []里面什么也没有!!
    fmt.Println(slice1)
}

2、 从数组中干获取Slice

func main() {
    
    arr := [3]int32{1, 2, 3} // 定义一个数组
    slice := arr[0:len(arr)] //从数组中取得Slice,从0开始,取到结束
    fmt.Println(slice)
}

//output
[1 2 3]

3、使用“make”关键字创建Slice

make([]T, len, cap)

[]T - 表示定义那种类型的Slice

len - 表示Slice的长度

cap - 表示Slice的容量;可以省略,即cap=len

s1 := make([]int, 3, 5)
fmt.Println(s1)

//output
[0 0 0]

Slice与底层数组的关系图

通过关系图,我们可以得出: Slice_a 长度为3,容量为9, Slice_b 长度为2,容量为8

Reslice

有 Slice 再次生成的Slice。它的特点是:

1. 索引以Slice为准。

2. cap不能超过Slice

3. 索引越界不会从新分配内存,而是直接出错!!

a2 := [5]byte{'a', 'b', 'c', 'd', 'e'}
s2 := a2[0:3]
fmt.Println(len(s2), cap(s2)) // output 3, 5

s22 := s2[0:2]
fmt.Println(len(s22), cap(s22)) // output 2, 5

Append 函数

a3 := make([]int32, 2, 4)
fmt.Printf("%v, %p
", a3, a3)

a3 = append(a3, 1, 2)
fmt.Printf("%v, %p
", a3, a3)

a3 = append(a3, 1, 2)
fmt.Printf("%v, %p
", a3, a3)

//output
[0 0], 0x114821d0
[0 0 1 2], 0x114821d0
[0 0 1 2 1 2], 0x11489c60

copy 函数

copy(src, dst) - 将dest的切片 copy 到 src, 以两者之中最短的切片长度为准。

a1 := []int32{1, 2}
a2 := []int32{3, 4, 5}
fmt.Println(a1) // output [1 2]

copy(a1, a2)
fmt.Println(a1) // output [3 4]

copy(a1[0:2], a2[1:3]) // // output [4 5]
fmt.Println(a1)
原文地址:https://www.cnblogs.com/atuotuo/p/6833198.html