Published on

How to append to a slice in golang?

How to append to a slice in golang?

The append() Function: Adding Elements to a Slice

In Go, the append() function plays a pivotal role when it comes to adding elements to a slice. It provides a seamless way to extend the size of a slice dynamically.

The append() function takes in a slice and one or more elements to be appended, and it returns a new slice with the added elements.

Here's the general syntax of the append() function:


    newSlice := append(existingSlice, element1, element2, ...)

Let's walk through an example to solidify our understanding:

    package main

    import (
        "fmt"
    )

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

        fmt.Println("Original Slice:", slice)
        fmt.Println("New Slice:", newSlice)
    }

    Original Slice: [1 2 3]
    New Slice: [1 2 3 4]

Capacity Considerations

While appending elements to a slice, it's important to understand how Go manages the underlying array's capacity. When the underlying array's capacity is sufficient to accommodate the new elements, the append() operation is efficient as it simply adds the elements to the existing array. However, when the capacity is exceeded, Go will create a new, larger array, copy the existing elements, and then add the new elements.

This capacity management strategy ensures that the append() operation maintains a balance between efficiency and memory usage. Developers should be mindful of potential reallocations when working with large slices to avoid unnecessary performance overhead.

Appending Slices: A Hierarchical Approach

In some scenarios, you might want to append the contents of one slice to another. This can be achieved using the ... ellipsis operator to unpack elements from one slice into another.

Consider the following example:

    package main

    import (
        "fmt"
    )

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

        fmt.Println("Combined Slice:", combinedSlice)
        //  Combined Slice: [1 2 3 4 5 6]
    }