How to Append Slice in Golang

Golang slice is a reference to the contiguous segment of the array. Slice is the pointer, with additional properties about an array.

How to append slice in Golang

To append a slice in Golang, use the slice.append() function. Go append.slice() is a built-in function that appends any number of elements to the end of a slice.

The slice append() function returns the updated slice and does not modify the existing one. The resulting value of the append() function is a slice containing all the elements of the original slice plus the provided values.

A slice consists of 3 fields.

  • The Pointer to the underlying array.
  • Length of the slice.
  • The capacity of the slice.

Slicing does not copy the slice’s data. It creates the new slice value that points to an original array. It makes slice operations as efficient as manipulating the array indices.

If we want to increase the capacity of the slice, we must create a new, larger slice and copy the contents of an original slice into it.

Due to this technique, how the dynamic array implementations from other languages work behind the scenes.

Let’s see the syntax of the Golang Slice append() function.

func append(s []T, x ...T) []T

The append function appends the items x to the end of the slice s and grows the slice if greater capacity is needed.

Now, let’s see the example of appending an item to Slice.

/* hello.go */

package main

import "fmt"

func newChar() string {
   return "Jon Snow"

func main() {
   characters := []string{"Tyrion Lannister", newChar()}
   characters = append(characters, "Daenerys Targaryen")
   fmt.Println("The characters of Game of Thrones are: ", characters)

First, we have defined a slice with initial data in the above code.

Then we have appended one more string to the characters array, but it will create a new array and then return it. So no side effects should be there.

The output of the code is the following.

Go Slice Append Example

Let’s see another example.

/* hello.go */

package main

import "fmt"

func main() {
   apps := []string{"Facebook", "Instagram", "WhatsApp"}
   newApps := []string{"Uber", "Ola"}
   apps = append(apps, newApps...)
   fmt.Println("All IMP Apps are: ", apps)

In the above code, we have first defined the two slices.

Then, we have appended apps slice to the newApps slice.

The (…) unpacks the newApps slice. Without the three dots, the code would attempt to append the slice as a whole, which is invalid.

The output of the code is the following.

Go Slice Append Example | Golang Append Tutorial

That’s it for this tutorial.

Recommended Posts

Golang For Loop

Golang Custom Type Declaration

Golang Receiver Function

Interface Implementation in Golang

Golang array

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.