AppDividend
Latest Code Tutorials

Go Slice Append Example | Golang Append Tutorial

0

Go Slice Append Example | Golang Append Tutorial is today’s topic. The built-in append function appends any number of elements to the end of a slice. Append returns the updated slice and it does not modify the existing one. So it is Pure function in terms of Javascript. The resulting value of append() function is a slice containing all the elements of the original slice plus the provided values.

Go Slice Append Example

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

A slice is 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, one must create the 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 Go 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)
}

In the above code, first, we have defined a slice with initial data.

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 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 following.

 

Go Slice Append Example | Golang Append Tutorial

Finally, Go Slice Append Example | Golang Append Tutorial is over.

Leave A Reply

Your email address will not be published.

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