A slice is a flexible and extensible data structure used to store and manage a collection of ordered data. They are very similar to arrays with one major difference: slices are of dynamic length, allowing you to expand or shrink their length as you see fit.

Similar to arrays, we use indexes to access elements in a slice. They also have length and capacity properties.

In this guide, we will discuss how to work with slices and how to add or remove items from a slice as you see fit.

Go Create Slice

You can create a slice similarly to what you would when creating an array. We start with the name of the array, followed by a pair of square brackets and the data type.

Keep in mind that a slice can only hold elements of the same type.

Consider the example below to create an empty array:

To create a slice with elements, we can do:

var slice_name :=  []string{“element1”, “element2”, “element3”, …}

Print Slice

You can print a slice using the fmt.Println method. For example:

package main


import “fmt”


func main() {


    my_slice := []string{


        “Winnie”,


        “Rick”,


        “Anna”,


        “Elsa”,


        “Olaf”,


    }


    fmt.Println(“Slice: “, my_slice)

}

The example above returns each element in the slice as shown below:

Slice:  [Winnie Rick Anna Elsa Olaf]

To show the length of the slice, you can use the len() method:

fmt.Println(“Lenght: “, len(my_slice))

An example output is as shown:

You can also determine the capacity of a slice using the cap() method as shown:

fmt.Println(“Capacity: “, cap(my_slice))

Output is as shown:

The length of the array refers to the total number of elements an array holds. In contrast, capacity refers to the number of elements of the underlying array from the first element in the specified slice.

Append to Slice

As mentioned, a slice is of dynamic size. This allows you to add or remove elements as you see fit.

To add an element to a slice in go, we can use the append() method.

An example is as shown:

 my_slice := []string{


    “Winnie”,


    “Rick”,


    “Anna”,


    “Elsa”,


    “Olaf”,

}


my_slice = append(my_slice, “David”,)

The append() method takes the name of the slice and the new element to add. In the example above, we add the element “David” to the slice “my_slice”.

The resulting slice is as shown:

Slice:  [Winnie Rick Anna Elsa Olaf David]

You can add multiple elements using the append() function as:

my_slice = append(my_slice, “David”, “Mary”)

NOTE: A slice will always maintain the order of elements, and new elements are appended at the end of the slice.

You can also append a slice to another slice as shown:

    my_slice := []string{


        “Winnie”,


        “Rick”,


        “Anna”,


        “Elsa”,


        “Olaf”,


    }


    second_slice := []string {


        “Emma”,


        “Matthew”,


    }


    my_slice = append(my_slice, second_slice…)


    fmt.Println(“Slice: “, my_slice)

We append a slice to an existing slice using the append() method in the example above.

Pay attention to the “…” operator in the second slice. This tells the compiler that the second argument should be expanded and each element passed to the append function as individual components. This is known as a variadic parameter.

The resulting slice as:

Slice:  [Winnie Rick Anna Elsa Olaf Emma Matthew]

Go Iterate Slice

You can use a for loop to iterate over the items of a slice. An example is a shown below:

for index, element := range my_slice {


    fmt.Printf(“Element at index %d => %s n, index, element)

}

In the example above, we use a range for loop to iterate over each item of the slice. We use the index to retrieve the element as shown in the output below:

Element at index 0 => Winnie


Element at index 1 => Rick


Element at index 2 => Anna


Element at index 3 => Elsa


Element at index 4 => Olaf


Element at index 5 => David


Element at index 6 => Mary

Conclusion

This guide covered the basics of working with slices in the go programming language. Using slices, you can introduce flexibility to your programs.

Thanks for reading!

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352b58b83d.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list