Working with Slices in Go

11.10.2021

Intro

Slices are super charged arrays. They allow you to dynamically build, add, and modify lists. Similar to arrays, they must have the same site, but they don't require a static size. In this article, we will learn about Slices in Go.

Creating a Slice

To create a slice, we define it similar to an array, but we don't need to specify a size.

var list = []int

We can also initialize our slice with values.

var list = []int {1, 2, 3}

Getting the Length of a Slice

To get the length of a slice, we can use the len function.

var list = []int {1, 2, 3}
fmt.Println(len(list)) // 3

Indexing

Now that we can create a list, let's see how to index or subslice our list. We can do this by passing indexes to the [] operator.

var list = []int {1, 2, 3}


fmt.Println(list[1]) // 1

fmt.Println(list[1:3]) // 1, 2, 3

fmt.Println(list[:3]) // 1, 2

fmt.Println(list[1:]) // 2, 3

We can also use indexing to modify our list.

list[1] = 4
fmt.Println(list[1]) // 4

Appending

To add items to our list, we can use the append function.

list = append(list, 4)
fmt.Println(list) // [1 2 3 4]

Copying Slices

We can also copy a slice using the copy function. We also have to use the make function to allocate space to the slice we want to copy to.

var list2 []int = make([]int, len(list))
copyCount := copy(list2, list)
fmt.Println(list2) // [1 2 3 4]
fmt.Println(copyCount) // 4

Default Slices

One interesting property of slices is that they equal nil by default. So if you want to check for an empty list, you can use this property.

var list3 []int
if list3 == nil {
	fmt.Println("List is empty")
}

Full Example

Here is the full example code.

package main

import "fmt"

func main() {
	var list = []int{1, 2, 3}

	fmt.Println(list[1]) // 2

	fmt.Println(list[1:3]) // 2, 3

	fmt.Println(list[:3]) // 1, 2 3

	fmt.Println(list[1:]) // 2, 3

	list[1] = 4
	fmt.Println(list[1]) //

	list = append(list, 4)
	fmt.Println(list) // [1 2 3 4]

	var list2 []int = make([]int, len(list))
	copyCount := copy(list2, list)
	fmt.Println(list2) // [1 2 3 4]
	fmt.Println(copyCount)

	var list3 []int
	if list3 == nil {
		fmt.Println("List is empty")
	}
}

You can run this by copying the contents to a file called main.go and run go run main.go.