Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

append
slice
golang
go

How to append to a slice in Golang

Educative Answers Team

Since slices are dynamically-sized, you can append elements to a slice using Golang’s built-in append method.

The syntax of the append method is as follows:

svg viewer
slice = append(slice, elem1, elem2, ...)

The first parameter is the slice itself, while the next parameter(s) can be either one or more of the values to be appended. The resulting value of append is a slice containing all the elements of the original slice plus the provided values. The original slice is not directly affected by append.

If the backing array of s is too small to fit all the given values, a bigger array will be allocated. The returned slice will point to the newly allocated array.

Code

The code snippet below demonstrates how to append a slice in Golang:

package main
import "fmt"

// Helper function to. print slices
func printSlice(s []int) {
	fmt.Printf("length=%d capacity=%d %v\n", len(s), cap(s), s)
}

func main() {
	var slice []int // Create an empty slice of type int.
	printSlice(slice)

	// Append works on nil slices.
	slice = append(slice, 0)
	printSlice(slice)

	// Slices can be appended to as many times.
	slice = append(slice, 1)
	printSlice(slice)

	// We can add more than one element at a time.
	slice = append(slice, 2, 3, 4)
	printSlice(slice)
}

RELATED TAGS

append
slice
golang
go
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring