Slices in Go

Alissa LozhkinAlissa Lozhkin
2 min read

Another datatype similar to arrays but less restrictive is a slice. Slices are less restrictive than arrays because they can dynamically grow and shrink in size. Therefore, we can easily append to or remove an element from them. This post will go over the steps on how to initialize a slice and also how to append to and remove from a slice.

There are a few ways to initialize a slice. The first way is very similar to how we initialize an array:

var slice1 = []int{} // initializes an empty slice with undefined length
var slice2 = []int{1, 2, 3}  // initalizes a non-empty slice

Note that in the square brackets on the right side of the equal sign, no length is specified (unlike for an array).

The second way is to create a slice from an array:

var arr1 = [5]int{1, 2, 3, 4, 5}
slice3 := arr1[1:4]  // slice3 = [2, 3, 4]

When a slice is created from an array, it is a pointer to a specific section of the array. Because of this, when modifying a slice, the same modifications will show up in the underlying array. This can be illustrated in the code block below:

slice3[0] = 44  // slice3 = [44, 3, 4]
fmt.Println(arr1)  // [1, 44, 3, 4, 5]

Elements can be added to a slice simply by using the "append" function. The first argument of this function is a slice and the rest are values that should be appended to the final slice. In the code below, we update the value of slice4 to be the original slice4 (containing values 5, 6, and 7) plus the values 8, 9, and 10:

var slice4 = []int{5, 6, 7}  // slice4 = [5, 6, 7]
slice4 = append(slice4, 8, 9, 10)  // slice4 = [5, 6, 7, 8, 9, 10]

Removing an element from a slice is done by using the "append" function as well. The code block below gives an example of how this is done:

var slice5 = []int{1, 2, 3, 4, 5}  // slice5 = [1, 2, 3, 4, 5]
slice5 = append(slice5[:2], slice5[3:]...)  // slice5 = [1, 2, 4, 5]

We can see that the value at the second index of "slice5" is removed by updating the value of "slice5" to be slice5[:2] plus slice5[3:] ([1, 2] + [4, 5]).

0
Subscribe to my newsletter

Read articles from Alissa Lozhkin directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alissa Lozhkin
Alissa Lozhkin

My name is Alissa and I am a fourth-year computer science and math student at the University of Toronto! I am very interested in computer science and software development, and I love learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin