SoFunction
Updated on 2025-03-05

Detailed explanation of Append usage examples in Golang

Use of append function:

Append can append an element, multiple elements, and new slices to a slice

var x []int

x = append(x, 1) // Append an elementx = append(x,2,3,4) //Add multiple elementsx = append(x, []int{5,6,7}...) //Add a new slice

Adding a slice requires unpacking

The principle of append()

1. If the original slice capacity is large enough, the append() function will create a new slice, which shares the underlying memory with the old slice

Creation principle:newSlice = oldSlice[:1+len(x)]

Create by assigning values ​​to new slices by old slice, and the memory will be shared. And return to this new slice.

Therefore, for insurance, we usually assign the content returned by append to the original slice: x = appen(x,…)

2. If the original slice does not have enough capacity to add content, create a new slice, which is the old slice of copy. Don't share memory with old slice

Example: appendInt()

This is an example of only one element being added

Before appending, determine whether cap(x) is sufficient.

  • If sufficient, the z size created is len(x) + 1
  • If not enough, create a z that is twice the size of the original
func appendInt(x []int, y int) []int {
	var z []int        // Create an intermediate array	zlen := len(x) + 1 // Prepare to add an element's position
	// Determine whether x's cap is enough to accommodate new elements	if zlen <= cap(x) {
		// Enough capacity, copy x to y directly		z = x[:zlen]
		//If the capacity is sufficient, you need to install a z, which is one seat larger than x, so you need to copy the empty space behind x as well.	} else {
		// x is not enough capacity		zcap := zlen // If xlen == 0		if zcap < 2*len(x) {
			zcap = 2 * len(x) //Create as double the original		}
		z = make([]int, zlen, zcap)
		copy(z, x)
	}

	z[len(x)] = y // Put y in the last position
	return z
}

test:

func main() {
	var x, y []int
	for i := 0; i < 10; i++ {
		y = appendInt(x, i)
		("%d cap=%d\t%v\n", i, cap(y), y)
		x = y
	}
}

Changes in capacity each time:

0  cap=1    [0]
1  cap=2    [0 1]
2  cap=4    [0 1 2]
3  cap=4    [0 1 2 3]
4  cap=8    [0 1 2 3 4]
5  cap=8    [0 1 2 3 4 5]
6  cap=8    [0 1 2 3 4 5 6]
7  cap=8    [0 1 2 3 4 5 6 7]
8  cap=16   [0 1 2 3 4 5 6 7 8]
9  cap=16   [0 1 2 3 4 5 6 7 8 9]

Copy: Assigned copy difference

=Assigning a copy will copy the original slice address and share memory with the old and new slices.

copy(new, old)The function copy will only copy the slice content.

	var x, y []int
	x = []int{1, 2, 3, 4}
	(x, y) // [1 2 3 4] []
	y = x
	y[0] = 0
	("y changed: ", x, y) //[0 2 3 4] [0 2 3 4]

Supplementary knowledge: golang append tips

package main

import (
	"fmt"
)

func main() {
	//Define an int array initializes to 1 2 3 4	var test []int = []int{1, 2, 3, 4}
	//If I want his value to become 1 2 3 4 5 6 7, you can use the append built-in function	/*
		 append is mainly used to append elements to a slice;
		 If the slice storage space (cap) is sufficient, it will be added directly and the length (len) becomes longer;
		 If there is insufficient space, the memory will be re-opened and the previous elements and new elements will be copied into it;
		 The first parameter is a slice, followed by a variable parameter of the slice storage element type;
	 */
	test = append(test, 5)
	test = append(test, 6)
	test = append(test, 7)
	//Now we get the desired result, but we have written 3 lines. There is a trick to directly write one line to solve the battle.	//Open a slice directly	(test)
	//Of course, this writing will definitely report an error.	//cannot use []int literal (type []int) as type int in append
	//He will tell you that the normal use should be the int type instead of the []int type	test = append(test, []int{5, 6, 7})
	//The correct way to play remember to add 3 points	test = append(test, []int{5, 6, 7}...)
	(test)
}

Summarize

This is the end of this article about the use of Append() in Golang. For more detailed explanations of Golang Append(), please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!