How to append a slice in Golang?


Appending a slice in Golang is a common operation when working with collections of data. In this article, we will explore how to append a slice in Golang.

Syntax for Appending a Slice in Golang

slice = append(slice, element)

The append() function in Golang appends the given element(s) to the end of a slice and returns a new slice. If the original slice has enough capacity to hold the new elements, the underlying array is reused, else a new array is allocated.

Example

Here's an example of how to append a slice in Golang.

package main

import (
   "fmt"
)

func main() {
   slice1 := []int{1, 2, 3}
   slice2 := []int{4, 5, 6}

   // Append slice2 to slice1
   slice1 = append(slice1, slice2...)

   fmt.Println(slice1) // [1 2 3 4 5 6]
}

Output

[1 2 3 4 5 6]

In this example, we define two integer slices slice1 and slice2. We then use the append() function to append slice2 to slice1. Note that the ... syntax is used to unpack slice2 into individual elements.

The append() function can also be used to append a single element to a slice. Here's an example −

Example

package main

import (
   "fmt"
)

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

   // Append element 4 to slice
   slice = append(slice, 4)

   fmt.Println(slice) // [1 2 3 4]
}

Output

[1 2 3 4]

In this example, we define an integer slice slice. We then use the append() function to append the integer 4 to slice.

Conclusion

Appending a slice in Golang is a simple operation that can be achieved using the append() function. This function allows you to add new elements to an existing slice without having to manually manage the underlying array.

Updated on: 19-Apr-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements