Gaaker Go

Golang Appending to a slice

Appending new elements to a slice is a common operation, for which Go provides a built-in append function.

func append(slice []T, elems ...T) []T

If the slice capacity is sufficient, the target will be sliced again to accommodate the new element.

If the slice capacity is not enough, a new array will be allocated. append returns an updated slice. Therefore, it is necessary to store the result of append in a variable that holds the slice itself.

The following is a complete code example.

package main

import "fmt"

func main() {
	s := make([]int, 3, 4)
	printSlice(s)
    // 切片容量足够
	s = append(s, 1)
	printSlice(s)

	// 切片容量不够
	s = append(s, 1)
	printSlice(s)

	// 可以一次性添加多个元素
	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)
}

Below is the program output:

len=3 cap=4 [0 0 0]
len=4 cap=4 [0 0 0 1]
len=5 cap=8 [0 0 0 1 1]
len=8 cap=8 [0 0 0 1 1 2 3 4]
< Appending to a slice Appending to a slice >