Selecting a Part of a Slice

Let’s learn how to select a part of a slice in the Go language.

How to select a part of a slice

Go allows us to select parts of a slice, provided that all desired elements are next to each other. This can be pretty handy when we select a range of elements and we do not want to give their indexes one by one. In Go, we select a part of a slice by defining two indexes: the first one is the beginning of the selection, whereas the second one is the end of the selection, without including the element at that index, separated by :.

Note: If we want to process all the command-line arguments of a utility apart from the first one, which is its name, we can assign it to a new variable (arguments := os.Args) for ease of use and use the arguments[1:] notation to skip the first command-line argument.

However, there is a variation where we can add a third parameter that controls the capacity of the resulting slice. So, using aSlice[0:2:4] selects the first two elements of a slice (at indexes 0 and 1) and creates a new slice with a maximum capacity of 4. The resulting capacity is defined as the result of the 4-0 subtraction where 4 is the maximum capacity, and 0 is the first index—if the first index is omitted, it is automatically set to 0. In this case, the capacity of the result slice will be 4 because 4-0 equals 4.

If we had used aSlice[2:4:4], we would have created a new slice with the aSlice[2] and aSlice[3] elements and with a capacity of 4-2. Lastly, the resulting capacity can’t be bigger than the capacity of the original slice because, in that case, we would need a different underlying array.

Coding example

Let’s understand how we can select a part of a slice using the following partSlice.go code example.

Get hands-on with 1200+ tech skills courses.