https://go.dev/tour/moretypes/15

附加到切片 : 将新元素附加到切片是很​​常见的,因此 Go 提供了一个内置的

append
功能。 文档 _ 内置包的描述
append
.

func append(s []T, vs ...T) []T 

第一个参数

s
append
是类型的一部分
T
,其余的是
T
要附加到切片的值。

结果值

append
是包含所有元素的切片 原始切片加上提供的值。

如果支持数组

s
太小而无法适应所有给定的值 数组将被分配。 返回的切片会指向新分配的 大批。

package main
import "fmt"
func main() {
    var s []int
    printSlice(s)
    // append works on nil slices.
    s = append(s, 0)
    printSlice(s)

 

    // The slice grows as needed.
    s = append(s, 1)
    printSlice(s)     // We can add more than one element at a time.
    s = append(s, 2, 3, 4)
    printSlice(s)
} func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

go run appending_to_slice.go
len=0 cap=0 []
len=1 cap=1 [0]
len=2 cap=2 [0 1]
len=5 cap=6 [0 1 2 3 4]