Golang: Append to Slice

By Xah Lee. Date: . Last updated: .

Append to Slice

The append is a critical function in golang. It's used to append, prepend, join, slices, or delete elements in slice. You need to pay attention whether it returns a new slice or just modify the original.

append(slice_var, newItem1, newItem2, etc)
  • Append new items to a slice variable slice_var
  • Return new value of slice_var

The result slice_var is a newly constructed slice if the result is more than the original slice's capacity.

🛑 WARNING: make sure you know if you are appending beyond capacity. This is critical if the original slice is a slice of slice. For example, if you have slice aa, and a slice of that bb, and you append to bb. Now, change to bb may or may not change aa, depending on if the append created a new.

Example: Basic Append

package main

import "fmt"

func main() {

	var s1 = []int{3, 5}
	var s2 = append(s1, 8, 9)

	fmt.Println(s2) // [3 5 8 9]

	// original not changed, in this case
	fmt.Println(s1) // [3 5]

}

Example: Append May or May Not Share Original Slice Data

Append creates a new slice ONLY WHEN the result is beyond original capacity.

package main

import "fmt"

func main() {

	var x1 = []int{0, 1, 2, 3, 4, 5}
	var x2 = x1[:3] // [0 1 2]
	var x3 = append(x2, 99)

	// x1 is changed
	fmt.Println("x1 is", x1)
	// x1 is [0 1 2 99 4 5]

	// x2 no change
	fmt.Println("x2 is", x2)
	// x2 is [0 1 2]

	// x3
	fmt.Println("x3 is", x3)
	// x3 is [0 1 2 99]

	// HHHH------------------------------

	// if the append added more items than the capacity of x1, then x1 will not be changed
	// now we do the above again to see

	var y1 = []int{0, 1, 2, 3, 4, 5}
	var y2 = y1[:3] // [0 1 2]

	var y3 = append(y2, 21, 22, 23, 24, 25)

	fmt.Println(y3) // [0 1 2 21 22 23 24 25]

	// y1 is not changed
	fmt.Println(y1) // [0 1 2 3 4 5]

}

Join Slices

Use triple dots operator to turn a slice into function arguments, then use append.

append(slice_var, slice_y ...)

package main

import "fmt"

func main() {

	var s1 = []int{3, 5}
	var s2 = []int{6, 7}
	var s3 = append(s1, s2...)

	fmt.Println(s3) // [3 5 6 7]

}

Append String as Byte Slice to Slice

Use triple dots operator to turn a string into byte slice, then use append.

append(slice_var, string ...)

Golang, array and slice