Skip to content

Golang Slice Append: One or Multiple Items

Append is a basic function you need to learn when you are working with slices in golang:

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

This example shows you three ways of appending into a slice: one item, multiple items, or items of a slice with the same type:

package main

import "fmt"

func main() {
	firstSlice := []int{1, 2}

	// append one item
	result := append(firstSlice, 3)

	// append multiple items
	result = append(firstSlice, 4, 5, 6)

	fmt.Println(result)

	secondSlice := []int{7, 8}

	// append a slice items
	result = append(result, secondSlice...)

	fmt.Println(result)
}

Leave a Reply

Your email address will not be published. Required fields are marked *