Close this search box.

Golang: Arrays and Slices in Go

Go has two array-like data structures. The first, is called an array; it’s a fixed length list of things, once it’s defined, you can’t add or remove anything from that list; a bit like a tuple in Python.

The second type is called a slice. This is an abstraction of the array data type and it actually sits on top of an underlying fixed length array, but we don’t need to worry about that – it gives us the ability to grow or shrink our list by adding or removing items from it.

Whether it’s a slice or an array, it’s important to note that all items within those lists must be of the same data type.

We define an array by writing var a[5] int, which gives us an array with a length of 5. Note that when we don’t declare what’s included in the array, all five elements will be set to zero by default.

We can set the specific values if we like by using: a := [5]int{5, 10, 20, 15, 2}. Here, we’ve defined what the five values in the array will be.

We can set the value for a specific index of the array by typing: a[2] = 7. As you can see below, this changes the original entry of 20 to a new entry of 7 in position 2 of the array (arrays are zero indexed).

Creating a slice is as simple as removing the 5 (the length of the array). This will give us the ability to add or remove items. Before we do that, let’s see what happens if we try to add a value to the array we already defined.

You can see, we got an error as the array cannot be appended to. So, let’s update our code to make that a slice and see what happens. Note, when we append, we don’t simply add an item to the list, it replaces the list. So you need to include the original list in the append statement.

So there we go, a really quick introduction to arrays and slices in Golang.

Share the Post:

Related Posts